gpt4 book ai didi

javascript - 悬停时的 Z 索引

转载 作者:行者123 更新时间:2023-12-03 04:36:57 25 4
gpt4 key购买 nike

对于我正在构建的网站,我有一个图像,其下方有一个浅灰色的 h1。当我将鼠标悬停在图像上时,文本应变为黑色,并且 z 索引应发生变化,使其位于图像上方。

颜色更改有效,但 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 包装器提供一个类,并且我们将标题放在它之后而不是之前(因为您在视觉上无论如何让它们重叠),我们可以使用 adjacent sibling combinator (+) 或 general (following) sibling combinator (~) 和 :hover 伪类:

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

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

#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 上使用的类:

关于javascript - 悬停时的 Z 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com