[英]How to not apply CSS :hover to parent elements
I want :hover
not to be applied to parent elements, and when :hover
is applied to the child, it also applies to parent divs.我希望:hover
不应用于父元素,当:hover
应用于子元素时,它也适用于父 div。
div{ min-width:50px; min-height:50px; padding:12px; background:#0002; } div:hover{ background:#f204; border:2px dashed #f20; }
<!DOCTYPE html> <html> <head> </head> <body> <div> It work correct <div> how to hover this and parents don't not change back color <div> how to hover this and parents don't not change back color </div> </div> </div> </body> </html>
if you open inspector from your browser like chrome you can select element by a button from top left corner or use shortcut CTRL+SHIFT+C i want to make something like this如果您从浏览器(如 chrome)打开检查器,您可以通过左上角的按钮或使用快捷键 CTRL+SHIFT+C 来 select 元素,我想做这样的事情
only JavaScript work and css never can do this!只有 JavaScript 工作和 css 永远不能做到这一点!
const query = document.querySelectorAll('div'); for(let i = 0;i < query.length;i++){ query[i].addEventListener('mouseover',over); query[i].addEventListener('mouseout',out); } function over(event){ const element = event.target; element.setAttribute('hover','') } function out(event){ const element = event.target; element.removeAttribute('hover'); }
div{ min-width:50px; min-height:50px; padding:12px; background:#0002; } div[hover]{ background:#2f24; border:2px dashed #2a2; }
<!DOCTYPE html> <html> <head> </head> <body> <div> It work correct <div> hover this and parents don't not change back color <div> hover this and parents don't not change back color </div> </div> </div> </body> </html>
You have to use a more specific selector and cannot simply use div:hover
.您必须使用更具体的选择器,不能简单地使用div:hover
。 Try something like this:尝试这样的事情:
div { min-width:50px; min-height:50px; padding:12px; background:#0002; } div > div > div:hover{ background:#f204; }
<!DOCTYPE html> <html> <head> </head> <body> <div> It work correct <div> how to hover this and parents don't not change back color <div> how to hover this and parents don't not change back color </div> </div> </div> </body> </html>
This >
is called child combinator: https://www.w3.org/TR/selectors/#child-combinators这个>
被称为子组合器: https://www.w3.org/TR/selectors/#child-combinators
You can use the class as below您可以使用 class 如下
CSS File CSS 文件
div{
min-width:50px;
min-height:50px;
padding:12px;
background:#0002;
}
el3:hover{
background:#f204;
}
HTML File HTML 文件
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="el1"> It work correct
<div class="el2"> how to hover this and parents don't not change back color
<div class="el3"> how to hover this and parents don't not change back color </div>
</div>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.