简体   繁体   中英

how to trigger mouseover event only for an img element using javascript

I want my mouseover event to only trigger when I hover over an img element only. I used

document.getElementsByTagName('img').onmouseover=function(e){ }

but it doesn't works. How should i achieve this?

I think you should apply event listeners to elements one by one:

 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"> 

Here we extract map function from the Array.prototype so we can map a function over any iterable object, not just arrays.

The same code with regular ES5 syntax:

 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"> 

getElementsByTagName returns a live HTMLCollection of elements. You need to set the event on all elements and not on the Collection.

You can do that like :

var arrElem = document.getElementsByTagName('img');

for (var i = arrElem.length; i-- ;) {
  arrElem[i].onmouseover = function(e) {};
}

GetElementsByTagName return the Collection of elements. If the is only one img it will be the collection with one element. So you need to access property of this collection through [0] .

document.getElementsByTagName('img')[0].onmouseover=function(e){ }

Would any of these do what you want? You would need JQuery for it, but I'd recommend it anyway.

$('#img')
    .mousemove(function (event) {
        console.log('Mouse moved');
    })
    .mouseenter(function () {
        console.log('Mouse over');
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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