繁体   English   中英

使用“this”引用单个类元素

[英]Reference Individual Class Elements with 'this'

如果我使用mouseenter / mouseout事件循环遍历具有相同类的不同元素,并且我试图合并 'this' 关键字,那么 JS 只会在我悬停的元素上触发。 我无法让它工作。

我不再尝试使用“this”关键字来使代码更易于阅读。 我该如何处理它,以便只有悬停在上面的元素才会在循环元素时应用mouseentermouseout事件?

我不能使用 jQuery 解决方案。

代码笔: 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>

在你的两个函数中,你需要做的就是参考this 在这种情况下, this指的是您当前悬停在其上的.menu-item事件。

请注意,您可能还想为<a>标记子项附加一个处理程序,否则每当您将鼠标悬停在它们上方时,脚本就会认为您要离开<li>并尝试更改颜色。

这可以通过检查有问题的事件的toElementrelatedTarget来完成,然后检查它们是否是父<li>元素。

总而言之,您的代码将如下所示:

 // declare variable for the CSS class var menuItem = document.querySelectorAll('.menu-item'); // loop through CSS class to change background to red function myMouseEnter() { this.style.background = "red"; } // loop through CSS class to change remove red background function myMouseLeave() { // prevent the 'mouseout' from affecting the <a> children var e = event.toElement || event.relatedTarget; if (e.parentNode == this || e == this) { return; } this.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); }
 .menu-item { padding: 10px; font-family: arial; }
 <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>

请注意,功能本身不必再次遍历菜单项;)

希望这有帮助! :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM