我希望我的鼠标悬停事件仅在我将鼠标悬停在 img 元素上时触发。我用过
document.getElementsByTagName('img').onmouseover=function(e){ }
但它不起作用。我该如何实现?
最佳答案
我认为您应该将事件监听器逐一应用于元素:
const imgs = document.getElementsByTagName('img');
const map = fn => x => Array.prototype.map.call(x, fn);
map(img => {
img.addEventListener('mouseover', (e) => {
e.target.style.border = '1px solid red';
});
img.addEventListener('mouseleave', (e) => {
e.target.style.border = 'none';
});
})(imgs)
<img src="" width="100" height="100">
<img src="" width="100" height="100">
<img src="" width="100" height="100">
在这里,我们从 Array.prototype
中提取了 map
函数,因此我们可以将函数映射到任何可迭代对象,而不仅仅是数组。
具有常规 ES5 语法的相同代码:
const imgs = document.getElementsByTagName('img');
const map = function(fn) {
return function(x) {
Array.prototype.map.call(x, fn);
}
}
const sponge = 'http://vignette3.wikia.nocookie.net/spongebob/images/6/6f/SpongeBob_%286%29.png/revision/latest?cb=20140824163929';
map(function(img) {
img.addEventListener('mouseover', function(e) {
e.target.src = sponge;
});
img.addEventListener('mouseleave', function(e) {
e.target.src = '';
});
})(imgs)
<img src="" width="90" height="80">
<img src="" width="90" height="80">
<img src="" width="90" height="80">
关于javascript - 如何使用javascript仅为img元素触发鼠标悬停事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43806176/