悬停时的Z-index

时间:2017-04-06 11:49:57

标签: javascript html hover position z-index

对于我正在建设的网站,我的图像下面有一个浅灰色的h1。当我将鼠标悬停在图像上时,文本应变为黑色,z-index应该更改,使其位于图像上方。

颜色变化正常,z-index不起作用。我的h1有位置:相对添加到它,所以这不是问题。

$('#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")

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

$('#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代替。如果我们在a周围给img包装,我们将标题放在之后而不是之前(因为你在视觉上使它们重叠),我们可以使用adjacent sibling combinator+)或general (following) sibling combinator~)和:hover伪类:

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

如果用户悬停照片或标题,则会自动将标题变为黑色并将其向上移动:

#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与我们在.projects上使用的类结合使用:

相关问题