使用javascript在IE上添加img标签时,onmouseover不起作用 [英] onmouseover doesn't work when using javascript to add img tag on IE

查看:190
本文介绍了使用javascript在IE上添加img标签时,onmouseover不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些可以将img标签动态添加到div的javascript代码,并且img标签需要onmouseover和onmouseout处理程序.

I need some javascript code that dynamically adds an img tag to a div, and the img tag needs onmouseover and onmouseout handlers.

我可以在Firefox上运行它.但这在IE上并不完全有效.在IE上,添加了img标签,但是onmouseover和onmouseout处理程序未激活.

I have it working on Firefox. But it doesn't quite work on IE. On IE, the img tag is added, but the onmouseover and onmouseout handlers are not active.

代码如下:

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

推荐答案

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等).它们隐藏了浏览器的不一致之处,因此您不必担心编写上面的代码.

look into using one of the many popular javascript libraries (jquery, prototype, etc). they hide browser inconsistencies so you don't need to worry about writing code like above.

这篇关于使用javascript在IE上添加img标签时,onmouseover不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆