5

我需要一些将 img 标签动态添加到 div 的 javascript 代码,而 img 标签需要 onmouseover 和 onmouseout 处理程序。

我让它在 Firefox 上运行。但它在 IE 上不太适用。在 IE 上,添加了 img 标签,但 onmouseover 和 onmouseout 处理程序未激活。

这是代码:

<body>  
    <div id='putImageHere' />  

    <script type='text/javascript'>
        var node = document.getElementById('putImageHere');
        var img = document.createElement('img');
        img.setAttribute('src', 'http://sstatic.net/so/img/logo.png');
        node.appendChild(img);

        // first attempt, which works on Firefox but not IE
        img.setAttribute('onmouseover', "alert('mouseover')");
        img.setAttribute('onmouseout', "alert('mouseout')");

        // second attempt, which I thought would work on IE but doesn't
        img.addEventListener('mouseover', function() { alert('mouseover') }, false);
        img.addEventListener('mouseout', function() { alert('mouseout') }, false);
    </script>  
</body>  
4

4 回答 4

8
if (img.addEventListener) {
    img.addEventListener('mouseover', function() {}, false);
    img.addEventListener('mouseout', function() {}, false);
} else { // IE
    img.attachEvent('onmouseover', function() {});
    img.attachEvent('onmouseout', function() {});
}

研究使用许多流行的 javascript 库(jquery、prototype 等)之一。它们隐藏了浏览器的不一致性,因此您无需担心编写上述代码。

于 2009-11-12T18:42:22.987 回答
3
img.setAttribute('src', 'http://sstatic.net/so/img/logo.png');

根本不要setAttribute在 HTMLElement 上使用。Internet Explorer 中存在错误,与更具可读性的 DOM Level 1 HTML 替代方案相比,它没有任何帮助:

img.src= 'http://sstatic.net/so/img/logo.png';

IE 上的基本问题setAttribute是它的工作方式与普通属性访问相同,即使该属性与属性具有不同的名称或类型。所以这:

img.setAttribute('onmouseover', "alert('mouseover')");

和说的一样:

img.onmouseover= "alert('mouseover')";

这没有任何意义:该onmouseover属性与所有事件处理程序一样,应该是一个函数,而不是一个字符串。而是分配一个函数:

img.onmouseover= function() {
    alert('mouseover');
};

然后你也摆脱了将代码放在字符串中的讨厌的 eval 风格的做法。万岁!

至于,如果你为 IE(它有自己的疯狂事件监听系统)addEventListener添加一个后备调用,你就可以使用它。attachEvent但是在每个元素只有一个侦听器的常见情况下,坚持使用每个浏览器支持的onsomething老式分配事件处理程序要容易得多。

于 2009-11-12T19:04:07.937 回答
0

原来 IE 不支持 addEventListener 方法。您可以在此处查看解决方法。

无论如何,你为什么不使用 jQuery 呢?它几乎覆盖了所有的兼容性问题,有一些额外的东西,而且它完全摇滚。

于 2009-11-12T18:36:10.270 回答
0

Ob的答案显示了在不使用 JavaScript 库的情况下附加事件侦听器的正确方法(并且是第一个),但我想添加以下内容:

永远不要将 onmouseover/out 作为属性附加。基本上,你经历了不做的所有麻烦

只是为了在你的 JavaScript 中做到这一点。事件处理回调应始终通过IE 的attachEvent附加为事件侦听器,而 几乎所有其他人都应通过addEventListener附加。

于 2009-11-12T20:47:36.187 回答