给Javascript函数一个id或class

时间:2015-04-03 13:01:46

标签: javascript

我试图让img悬停在多个img的另一个img上。 在1 img它就像一个魅力,但现在我需要4个img的相同功能我该如何定义?

我目前的代码:

        function MouseRollover(MyImage) {
    MyImage.src = "images/massage.jpg";
}
    function MouseOut(MyImage) {
    MyImage.src = "images/wellness.jpg";
}

                <a href='wellness.html'> <img src="images/wellness.jpg"  
            onMouseOver="MouseRollover(this)" 
            onMouseOut="MouseOut(this)" /> </a>

1 个答案:

答案 0 :(得分:1)

为什么不将图像源作为参数传递?

function setSrc(MyImage, newSrc) {
    MyImage.src = newSrc;
}
<a href='wellness.html'>
    <img src="images/wellness.jpg"  
         onMouseOver="setSrc(this, 'images/massage.jpg')" 
         onMouseOut="setSrc(this, 'images/wellness.jpg')" />
</a>

或者事件最好不要两次传递wellness图像:

function setSrc(myImage, newSrc) {
    var original = myImage.src;
    myImage.src = newSrc;
    myImage.onmouseout = function(){ myImage.src = original; }
}
<a href='wellness.html'>
    <img src="images/wellness.jpg"  
         onMouseOver="setSrc(this, 'images/massage.jpg')" />
</a>

查看herehere了解类似问题和jQuery解决方案。