onmouseover doesn't work when using javascript to add img tag on IE

前端 未结 4 644
闹比i
闹比i 2021-01-13 14:24

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

I have it working on Firefox. But

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 15:14

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

    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.

提交回复
热议问题