onmouseover和onmouseout的一些問題思考
更新時間:2013年08月14日 09:26:43 作者:
這兩個事件的觸發(fā)表現(xiàn)真的就是你想要的嗎?在IE下確實有你需要的兩個這樣事件:onmouseenter 和 onmouseleave。但很不幸FF等其他瀏覽器并不支持
一個DIV層,當鼠標移進的時候會觸發(fā)onmouseover,移出的時候會觸發(fā)onmouseout。
很簡單的邏輯,這也是我們想要的!但隨之煩惱也就來了:onmouseover并不會只在移進時才觸發(fā),onmouseout也不會只在移出時才觸發(fā)!鼠標在DIV里面移動時也會可能觸發(fā)onmouseover或onmouseout。
在上圖中,對于'A'來說:當鼠標進入'A'(路徑'1′)時那么就會觸發(fā)'A'的onmouseover事件;接著鼠標移動到'B'(路徑'2′),此時'A'會觸發(fā)onmouseout(先)和onmouseover(后)事件。
由此可見,如果HTML元素(‘A'層)內還有其他元素(‘B','C'層),當我們移動到這些內部的元素時就會觸發(fā)最外層(‘A'層)的onmouseout和onmouseover事件。
這兩個事件的觸發(fā)表現(xiàn)真的就是你想要的嗎?也許你需要一個只在移進時才觸發(fā)的,一個只在移出時才觸發(fā)的事件,不管其內部是否還有其他元素….
解決方案
在IE下確實有你需要的兩個這樣事件:onmouseenter 和 onmouseleave。但很不幸FF等其他瀏覽器并不支持,只好模擬實現(xiàn):
document.getElementById('...').onmouseover = function(e){
if( !e ) e = window.event;
var reltg = e.relatedTarget ? e.relatedTarget : e.fromElement;
while( reltg && reltg != this ) reltg = reltg.parentNode;
if( reltg != this ){
// 這里可以編寫 onmouseenter 事件的處理代碼
}
}
document.getElementById('...').onmouseout = function(e){
if( !e ) e = window.event;
var reltg = e.relatedTarget ? e.relatedTarget : e.toElement;
while( reltg && reltg != this ) reltg = reltg.parentNode;
if( reltg != this ){
// 這里可以編寫 onmouseleave 事件的處理代碼
}
}
備注:
W3C在mouseover和mouseout事件中添加了relatedTarget屬性
•在mouseover事件中,它表示鼠標來自哪個元素
•在mouseout事件中,它指向鼠標去往的那個元素
而Microsoft在mouseover和mouseout事件中添加了兩個屬性
•fromElement,在mouseover事件中表示鼠標來自哪個元素
•toElement,在mouseout事件中指向鼠標去往的那個元素

很簡單的邏輯,這也是我們想要的!但隨之煩惱也就來了:onmouseover并不會只在移進時才觸發(fā),onmouseout也不會只在移出時才觸發(fā)!鼠標在DIV里面移動時也會可能觸發(fā)onmouseover或onmouseout。

在上圖中,對于'A'來說:當鼠標進入'A'(路徑'1′)時那么就會觸發(fā)'A'的onmouseover事件;接著鼠標移動到'B'(路徑'2′),此時'A'會觸發(fā)onmouseout(先)和onmouseover(后)事件。
由此可見,如果HTML元素(‘A'層)內還有其他元素(‘B','C'層),當我們移動到這些內部的元素時就會觸發(fā)最外層(‘A'層)的onmouseout和onmouseover事件。
這兩個事件的觸發(fā)表現(xiàn)真的就是你想要的嗎?也許你需要一個只在移進時才觸發(fā)的,一個只在移出時才觸發(fā)的事件,不管其內部是否還有其他元素….
解決方案
在IE下確實有你需要的兩個這樣事件:onmouseenter 和 onmouseleave。但很不幸FF等其他瀏覽器并不支持,只好模擬實現(xiàn):
復制代碼 代碼如下:
document.getElementById('...').onmouseover = function(e){
if( !e ) e = window.event;
var reltg = e.relatedTarget ? e.relatedTarget : e.fromElement;
while( reltg && reltg != this ) reltg = reltg.parentNode;
if( reltg != this ){
// 這里可以編寫 onmouseenter 事件的處理代碼
}
}
document.getElementById('...').onmouseout = function(e){
if( !e ) e = window.event;
var reltg = e.relatedTarget ? e.relatedTarget : e.toElement;
while( reltg && reltg != this ) reltg = reltg.parentNode;
if( reltg != this ){
// 這里可以編寫 onmouseleave 事件的處理代碼
}
}
備注:
W3C在mouseover和mouseout事件中添加了relatedTarget屬性
•在mouseover事件中,它表示鼠標來自哪個元素
•在mouseout事件中,它指向鼠標去往的那個元素
而Microsoft在mouseover和mouseout事件中添加了兩個屬性
•fromElement,在mouseover事件中表示鼠標來自哪個元素
•toElement,在mouseout事件中指向鼠標去往的那個元素
相關文章
ASP小貼士/ASP Tips javascript tips可以當桌面
今天看到《ASP小貼士/ASP Tips》 我也去把JavaScript的tips 下下來了。 看看是A4的。 自己把他改成1024 * 768 剛好可以用來做桌面2009-12-12Javascript Throttle & Debounce應用介紹
Throttle:無視一定時間內所有的調用Debounce:一定間隔內沒有調用時,接下來將為大家介紹下Throttle & Debounce的應用,感興趣的朋友可以參考下哈2013-03-03