【发布时间】:2017-08-01 21:38:17
【问题描述】:
如果我使用 mouseenter / mouseout 事件循环遍历具有同一类的不同元素,并且我正在尝试合并“this”关键字,因此 JS 仅在我悬停的元素上触发。但我无法让它工作。
我已经取消了使用“this”关键字的尝试,以使代码更易于阅读。我该如何处理它,以便只有被悬停的元素在循环遍历元素时应用mouseenter 和mouseout 事件?
我不能使用 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>
【问题讨论】:
标签: javascript html for-loop this dom-events