将鼠标悬停在其他单词上时更改文本颜色



当用户将鼠标悬停在单词 B 上时,如何更改单词 A 的文本颜色? 例如,当用户将鼠标悬停在 h1 "我的名字是"上时,另一个 h1 "Paul" 的文本应该变为白色。

这个问题有什么解决方案吗?提前感谢!

更新: 我希望当用户将鼠标悬停在"餐厅"一词上时,文本"不是a"和"但在这里为他们"变为白色,并且"restaurant"一词应变为红色。第二部分("餐厅"变成红色)工作正常,但第一部分不起作用

这是我使用的代码:

.headingRestaurant:hover textb {
color: blue;
}
.headingRestaurant:hover {
color: red;
}
<h1 class="textb">Not a <span id="heading1" class="headingRestaurant">restaurant</span>, <br> but here for them.</h1>

有几种方法可以做到这一点,但最简单的方法是使用同级组合器,但文本必须位于同一父元素旁边和内部。~ 组合器将在第一个元素之后选择任何同级元素,但必须在您悬停在元素之后出现。

最强大的一个是:has伪选择器,但这需要一些理解,并且尚未在所有浏览器中完全支持。

请参阅下面的示例

.texta:hover + .textb {
color:red;
}
<span class="texta">My name is</span>
<span class="textb">Paul</xpan>

编辑

在评论中,要求做一个解决方案,当底部文本悬停时,上面的文本会改变颜色。

这可以通过 :has.请注意,这不适用于Firefox(还!)或某些移动浏览器,但适用于Chrome,Edge和Safari桌面浏览器。有关详细信息,请参阅 caniuse.com。

.container:has(.texta:hover) .textb {
color:red;
}
<div class='container'><h1 class="textb">Not a</h1><h1 id="heading1" class="texta">restaurant</h1><div>

显示:flex 还有一种厚颜无耻的方法,通过将 flex 方向设置为列反转。您可以按相反的顺序放置 h1 块,但弹性框会在浏览器中反转它们。通过应用同级规则,它也可以以这种方式工作。不过,这可能会使将来进行更改有点混乱。

.container {
display:flex;
flex-direction: column-reverse;
}
.texta:hover ~ .textb {
color:red;
}
<div class='container'>
<h1 id="heading1" class="texta">restaurant</h1>
<h1 class="textb">Not a</h1>
</div>
编辑 #2

根据编辑的问题(同样,这在火狐上不起作用):

.headingRestaurant:hover + .textc {
color: white;
}
.headingRestaurant:hover {
color: red;
}
h1:has(.headingRestaurant:hover) .texta {
color:white;
}
<h1><span class='texta'>Not a</span><span id="heading1" class="headingRestaurant"> restaurant</span><span class='textc'>,<br> but here for them.</span></h1>

你可以像下面这样做:

.textb {
pointer-events: none;
}
.headingRestaurant {
pointer-events: initial;
}
.textb:hover {
color: blue;
}
.headingRestaurant:hover {
color: red;
}
<h1 class="textb">Not a <span id="heading1" class="headingRestaurant">restaurant</span>, <br> but here for them.</h1>

是的,有很多方法可以做到这一点。

<h1 id="a">Name A</h1>
<h1 id="b">Name B</h1>

如果#a#b之间还有其他元素,则可以执行以下操作:

#a:hover ~ #b {
color: blue
}

请注意,+~在所有浏览器中的工作方式相同

iF#b#a的死者,那么您可以这样做:

#a:hover #b {
color: blue
}

这也可以使用jQuery或JavaScript来完成。

单词是在 1 个标题中还是在 2 个标题中很重要。

当您将鼠标悬停在保罗这个名字上时,请注意差异

.texta, .textb {
color: orange;
cursor: pointer;
}
/* using one h1 with a span inside */
.texta:hover span {
color: blue;
}
/* using two h1's after each other */
.textb, .textb + h1 {
display: inline-block;
}
.textb:hover + h1 {
color: blue;
}
<h1 class="texta">My name is <span>Paul</span></h1>
<h1 class="textb">My name is</h1> <h1>Paul</h1>

更新您更新的问题可以通过这种方式使用 flex 和order属性完成

.textb {
display: flex;
}
#heading1 {
order: 2;
}
#heading1 + span + span {
order: 3;
}
#heading1:hover {
color: red;
}
#heading1:hover + span,
#heading1:hover + span + span {
color: #ddd; /* change to white */
}
<h3 class="textb">
<span id="heading1" class="headingRestaurant">&nbsp;restaurant&nbsp;</span>
<span>Not a</span>
<span>but here for them.</span>
</h3>

最新更新