请不要使用 jquery
我有以下带有 class=menu-list 的菜单,我希望在嵌套/子 ul li 元素悬停时,将父 li 元素的背景颜色更改为白色
代码和工作演示:
nav .menu-list{
background: white;
position: absolute;
margin-top: 60px;
padding: 12px 0;
display: none;
width: 68vw;
height: 100vh;
}
nav .menu-list li{
background: white;
display: block;
color: #000000;
position: relative;
padding: 0;
border-left: 24px white solid;
}
nav .menu-list li:hover{
background: #eee;
border-left: 24px #eee solid;
}
nav ul li:focus {
background: white;
}
nav ul li:focus ul {
display: block;
position: relative;
left: 0;
margin-left: -24px;
}
nav ul li ul li:hover {
background: white;
}
<nav>
<ul class="menu-list" style="display: block;">
<li tabindex="1" onclick="location.href='#/work'; dimScreen()">Work</li>
<li tabindex="2" onclick="dimScreen()">About
<ul>
<li onclick="location.href='#/about/what-we-do'">What we do</li>
<li onclick="location.href='#/about/how-we-work'">How we work</li>
<li onclick="location.href='#/about/leadership'">Leadership</li>
</ul>
</li>
</ul>
</nav>
最佳答案
首先,你 can't do this with CSS . CSS 不知道它的父元素是什么。
至于javascript,可以使用鼠标事件。这是 an example :
var parentOn = function(e) {
e.target.parentNode.style.backgroundColor = '#9d7';
}
var parentOff = function(e) {
e.target.parentNode.style.backgroundColor = '#97a';
}
var children = document.querySelectorAll('.child');
for (var x = 0; x < children.length; x ++) {
children[x].addEventListener('mouseover', parentOn);
children[x].addEventListener('mouseout', parentOff);
};
一些注意事项:
任何 JavaScript DOM 查询都会返回一个节点数组,因此您必须遍历它们以避免错误。 JQuery 很好地隐藏了这一点,因此它可能会造成混淆。
mouseenter 和 mouseleave 组合与 mouseover 和 mouseout 有细微差别,您可以 find out more here
研究如何使用 JavaScript 添加和删除类会比使用内联样式更好。 This answer will help .您将能够重用这些样式,并且它会更容易维护 - 我希望创建一个实用函数来处理这个问题,例如 JQuery 的
addClass()
。使用命名函数变量比匿名函数更清晰一些,也更容易重用。
关于javascript - 在悬停子 <ul> <li> 元素时更改父 <ul><li> 元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33070736/