好的,所以我将尝试尽可能清楚地说明这一点。我想编写一个函数,调用时会将 onmouseout
属性添加到图像。
在鼠标悬停在图像上之前。
<img src="myfile.jpg" onmouseover="function()" />
之后
<img src="myfile.jpg" onmouseover="function()" onmouseout="anotherFunction()" />
我还想用 function()
改变图片,然后 onmouseout 将图片设置回原来的。我知道如何在图像代码中使用 onmouseover 和 onmouseout 更改图片,但我正在尝试简化它,因为我必须执行大约 100 次图像更改操作,而且我不想多次写出代码。啊,我希望这很清楚。
最佳答案
这比你想象的要简单:
function SetImageSource(ele, url) {
ele.src = url;
}
<img src="myfile.jpg"
onmouseover="SetImageSource(this, 'someURL')"
onmouseout="SetImageSource(this, 'someOtherURL')" />
注意:内联 JavaScript 并不理想。我建议阅读 JS 中的事件处理。更具体地说,阅读有关附加到事件的信息。
根据说明进行编辑
<img id="imgMyImage" src="myfile.jpg"
onmouseover="SetImageSource(this, 'someURL')"
onmouseout="SetImageSource(this, 'someOtherURL')" />
function AddEvent(html_element, event_name, event_function)
{
if(html_element.attachEvent) //Internet Explorer
html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
else if(html_element.addEventListener) // Everything else
html_element.addEventListener(event_name, event_function, false);
}
AddEvent(document.getElementById('imgMyImage'),
'onmouseover',
// do something
);
附加信息
关于javascript - 使用 JavaScript 向图像添加 JavaScript 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13790742/