有两个标题,标题h1
和标题h2
h2
有一个很好的下划线效果设置在她身上,显示在鼠标上。
我想能够悬停在h2
以及上h1
,在h2
标题下开始下划线效果。
鼠标悬停效果在h2
上有效,但在h1
上无效。
为什么鼠标悬停在h1
上没有触发h2
下的下划线效果?
h2:after {
content: "";
display: block;
width: 10%;
padding-top: 1em;
border-bottom: 4px solid black;
transition: 0.25s;
}
h2:hover:after{ /* Works as expected */
width: 100%;
}
h1:hover h2:after{ /* Broken, does not trigger the h2 underline */
width: 100%;
}
<a href="#" >
<hgroup>
<div>
<div>
<h1>Heading One</h1>
</div>
</div>
</hgroup>
</a>
<h2>Heading Two</h2>
你写选择器的方式,它试图瞄准h2是h1的孩子,但你的html结构不反映这一点。
一个选项是添加一个选择器到外部a
,然后用+
相邻的兄弟选择器瞄准相邻的h2
下面的代码片段显示:
h2:after {
content: "";
display: block;
width: 10%;
padding-top: 1em;
border-bottom: 4px solid black;
transition: 0.25s;
}
h2:hover:after {
/* Works as expected */
width: 100%;
}
a:hover+h2:after {
/* hover applied to the containing element so we can target the adjacent h2 */
width: 100%;
}
<a href="#">
<hgroup>
<div>
<div>
<h1>Heading One</h1>
</div>
</div>
</hgroup>
</a>
<h2>Heading Two</h2>
h1:hover h2
选择器要求h2
是h1
的子节点。你只能对后代元素应用悬停样式。
因为h2没有嵌套到h1中,所以你不能在css中访问它。添加一点javascript就可以了。
const h1 = document.querySelector('h1');
const h2 = document.querySelector('h2');
h1.addEventListener('mouseenter', () => {
h2.classList.add('active');
})
h1.addEventListener('mouseout', () => {
h2.classList.remove('active');
})
h2:after {
content: "";
display: block;
width: 10%;
padding-top: 1em;
border-bottom: 4px solid black;
transition: 0.25s;
}
h2:hover:after,h2.active:after { /* Works as expected */
width: 100%;
}
<a href="#" >
<hgroup>
<div>
<div>
<h1>Heading One</h1>
</div>
</div>
</hgroup>
</a>
<h2>Heading Two</h2>