[英]How to grab element you are hovering over?
How do you grab the element you are currently hovering over using pure Javascript, no jQuery? 你如何使用纯 Javascript,没有jQuery抓住你当前悬停的元素?
<ul>
<li></li>
<li></li>
<li></li>
</ul>
(function() {
var item = document.querySelector('li');
function randomColor() {
return '#' + Math.random().toString(16).slice(2, 8);
}
item.onmouseover = function() {
this.style.backgroundColor = randomColor();
};
item.onmouseleave = function() {
this.style.backgroundColor = randomColor();
};
}());
The problem is that it only changes the color on one of the elements, but not the other 2 when hovering over. 问题是它只会在其中一个元素上改变颜色,而在悬停时只改变另外两个元素的颜色。
Solution thanks to RUJordan 解决方案感谢RUJordan
(function() {
var box = document.querySelectorAll('li');
function randomColor() {
return '#' + Math.random().toString(16).slice(2, 8);
}
for (var i = 0; i <= box.length; i++) {
box[i].onmouseover = function() {
this.style.backgroundColor = randomColor();
};
box[i].onmouseleave = function() {
this.style.backgroundColor = randomColor();
};
}
}());
querySelector
only returns the first index of the array of elements you would get back from that method. querySelector
仅返回从该方法返回的元素数组的第一个索引。
To get all li
, use querySelectorAll("li")
and loop through the elements node list (array like) to add eventListeners
to them. 要获取所有li
,请使用querySelectorAll("li")
并遍历元素节点列表(类似数组)以向其添加eventListeners
。
I don't use jquery. 我不使用jquery。 This function returns the element that triggered the event. 此函数返回触发事件的元素。
function eventTarget(e) {
return (e && e.target ? e.target : event.srcElement);
}
Does that help? 这有帮助吗? e is the event object, the event.srcElement is for internet explorer compatibility. e是事件对象,event.srcElement用于Internet Explorer兼容性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.