0
如果我用mouseenter/mouseout事件循环播放具有相同类的不同元素,并且试图合并'this'关键字,以便JS只触发元素I'徘徊在。尽管如此,我还是无法使用它。参考具有'this'的单个类元素
我已经剔除了使用'this'关键字来使代码更易于阅读的尝试。我该如何去做,以便只有被鼠标悬停的元素才有鼠标事件,然后将鼠标移出事件应用于它,同时循环元素?
我无法使用jQuery解决方案。
codepen笔:https://codepen.io/emilychews/pen/mMEEBw
代码如下:
JS
// declare variable for the CSS class
var menuItem = document.querySelectorAll('.menu-item');
//loop through CSS class to change background to red
function myMouseEnter() {
for (i = 0; i < menuItem.length; i++) {
menuItem[i].style.background = "red";
}
}
//loop through CSS class to change remove red background
function myMouseLeave() {
for (i = 0; i < menuItem.length; i++) {
menuItem[i].style.background = "none";
}
}
//event handler to add function on mouseenter
for (j = 0; j < menuItem.length; j++) {
menuItem[j].addEventListener('mouseenter', myMouseEnter, false)
}
//event handler to add function on mouseout
for (k = 0; k < menuItem.length; k++) { menuItem[k].addEventListener('mouseout', myMouseLeave, false)
}
CSS
.menu-item {padding: 10px;
font-family: arial;
}
HTML
<ul class="unclick--menuitems">
<li class="menu-item"><a href="//google.com">About</a></li>
<li class="menu-item"><a href="//google.com">Projects</a</li>
<li class="menu-item"><a href="//google.com">Contact</a></li>
</ul>
非常感谢你,这是一个伟大的/翔实的答案。 –