悬停时的 Z-index

Z-index on hover

对于我正在构建的网站,我有一个图像,其下方有一个浅灰色的 h1。当我将鼠标悬停在图像上时,文本应该变成黑色并且 z-index 应该改变以便它位于图像上方。

颜色更改有效,z-index 无效。我的 h1 有 position: relative 添加到它所以这不是问题。

$('#photo').mouseover(function() {
  $('#title').css.zIndex = "100"
  $('#title').css("color", "#000000")
});
#photo {
  z-index: 0;
  position: relative;
}

#photo:hover {
  z-index: 4;
  position: relative;
}

.titles {
  position: relative;
}

#title {
  position: relative;
}
<div class="projects">
  <h1 class="titles" id="title">Title</h1>
  <a href="#"><img src="https://graph.facebook.com/10158407872045403/picture?type=large" id="photo"></a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

或者我也尝试使用

$('#title').css("z-index", "0")

我做错了什么?

$('#title').css.zIndex = "100" 不正确,但是您说您尝试过的 $('#title').css("z-index", "0") 是正确的——只是,您在那里使用了 0 而不是 100。由于照片和标题都有z-index: 0并且照片在标题后面,所以照片获胜

如果您使用 $('#title').css("z-index", "100"),它会起作用(但请继续阅读):

$('#photo').mouseover(function() {
  $('#title').css("z-index", "100");
  $('#title').css("color", "#000000")
});
#photo {
  z-index: 0;
  position: relative;
  top: -4em;
}

#photo:hover {
  z-index: 4;
  position: relative;
}

.titles {
  position: relative;
  color: grey;
}

#title {
  position: relative;
}
<div class="projects">
  <h1 class="titles" id="title">Title</h1>
  <a href="#"><img src="https://graph.facebook.com/10158407872045403/picture?type=large" id="photo"></a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

(我还在照片中添加了 top: -4em;,所以它确实与标题重叠了。)


话虽如此,我会尝试使用 CSS 代替。如果我们在 img 周围给 a 包装器一个 class,并且我们将标题 放在 之后而不是之前(因为你是无论如何视觉上使它们重叠),我们可以使用 adjacent sibling combinator (+) or a general (following) sibling combinator (~) 和 :hover pseudoclass:

.photo-wrapper:hover ~ h1.titles, h1.titles:hover {
  z-index: 100;
  color: black;
}

如果用户将鼠标悬停在照片或标题上,标题会自动变黑并向上移动 z-order:

#photo {
  z-index: 0;
  position: relative;
}

#photo:hover {
  z-index: 4;
  position: relative;
}

.titles {
  position: relative;
  color: grey;
}

#title {
  position: relative;
  top: -4em;
}

.photo-wrapper:hover ~ h1.titles, h1.titles:hover {
  z-index: 100;
  color: black;
}
<div class="projects">
  <a href="#" class="photo-wrapper"><img src="https://graph.facebook.com/10158407872045403/picture?type=large" id="photo"></a>
  <h1 class="titles" id="title">Title</h1>
</div>


话虽如此,我不会像那样直接操纵 #title 的样式,我会使用 CSS 结合我们在 [=29= 上使用的 class ]: