2017-08-01 53 views
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> 

回答

1

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

注意,你也可能会想附加的处理程序<a>标签孩子,不然当你将鼠标悬停在他们,脚本会认为你是离开<li>,并试图改变颜色。

这可以通过检查toElement和事件的问题relatedTarget,然后检查这些是否是父<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>

注意函数本身不必通过菜单项循环再次;)

希望这有助于! :)

+0

非常感谢你,这是一个伟大的/翔实的答案。 –