3

我需要一些動態地將img標記添加到div的javascript代碼,而img標記需要onmouseover和onmouseout處理程序。當使用javascript在IE上添加img標記時,onmouseover不起作用

我使用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> 

回答

6
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,原型等)進行研究。他們隱藏瀏覽器的不一致,所以你不必擔心編寫如上所述的代碼。

0

原來IE不支持addEventListener方法。您可以檢查解決方法here

無論如何,你爲什麼不使用jQuery?它幾乎覆蓋了所有的兼容性問題,有一些額外的東西,它完全是岩石。

+1

謝謝!在IE上使用img.attachEvent。 有一個原因,我不能使用jQuery,但我的理由不適用於大約99.99%的人閱讀這個,所以我不會去進入它。 – 2009-11-12 18:44:21

3
img.setAttribute('src', 'http://sstatic.net/so/img/logo.png'); 

請不要在HTML元素使用setAttribute,在所有。有蟲子在它在Internet Explorer中,並沒有得到你什麼相比更具可讀性DOM 1級HTML替代:

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

setAttribute對IE的基本問題是,它的工作原理同普通財產訪問,即使該屬性具有與該屬性不同的名稱或類型。所以這個:

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

是一樣的話說:

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

這是沒有意義的:在onmouseover屬性,像所有的事件處理程序,應該是一個函數,而不是一個字符串。改爲分配一個功能:

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

然後你也擺脫了把代碼放在字符串中的討厭的eval風格的做法。萬歲!

至於addEventListener,如果您爲IE(其擁有自己的瘋狂事件偵聽器系統)添加回調attachEvent調用,則可以使用它。但是在通常的情況下,你只有每個元素都有一個監聽器,那麼堅持使用老派支持每個瀏覽器的onsomething-指派事件處理程序要容易得多。

+0

+1用於解釋爲什麼'setAttribute'在IE中不起作用 – 2010-05-17 20:05:18

0

Ob的回答顯示了附加的事件偵聽器,而無需使用JavaScript庫的正確方法(和是第一個),但我想補充以下內容:

的onmouseover /出不應該作爲屬性附加。基本上,你經歷了所有不做的麻煩

只是要在你的JavaScript中做到這一點。通過attachEvent(對於IE)和addEventListener幾乎適用於其他人,事件處理回調應始終作爲事件偵聽器附加。