很简单的逻辑,这也是我们想要的!但随之烦恼也就来了:onmouseover并不会只在移进时才触发,onmouseout也不会只在移出时才触发!鼠标在DIV里面移动时也会可能触发onmouseover或onmouseo">

首頁  >  文章  >  web前端  >  onmouseover和onmouseout的一些問題思考_基礎知識

onmouseover和onmouseout的一些問題思考_基礎知識

WBOY
WBOY原創
2016-05-16 17:25:481291瀏覽

一個DIV層,當滑鼠移進的時候會觸發onmouseover,移出的時候會觸發onmouseout。
onmouseover和onmouseout的一些問題思考_基礎知識 
很簡單的邏輯,這也是我們想要的!但隨之煩惱也就來了:onmouseover並不會只在移進時才觸發,onmouseout也不會只在移出時才觸發!滑鼠在DIV裡面移動時也會可能觸發onmouseover或onmouseout。
onmouseover和onmouseout的一些問題思考_基礎知識 
在上圖中,對於'A'來說:當滑鼠進入'A'(路徑'1′)時那麼就會觸發'A'的onmouseover事件;接著滑鼠移動到' B'(路徑'2′),此時'A'會觸發onmouseout(先)和onmouseover(後)事件。

由此可見,如果HTML元素('A'層)內還有其他元素('B','C'層),當我們移動到這些內部的元素時就會觸發最外層('A'層)的onmouseout和onmouseover事件。

這兩個事件的觸發表現真的就是你想要的嗎?也許你需要一個只在移進時才觸發的,一個只在移出時才觸發的事件,不管其內部是否還有其他元素….

解決方案

在IE下確實有你需要的兩個這樣事件:onmouseenter 和onmouseleave。但很不幸FF等其他瀏覽器不支持,只好模擬實作:

複製程式碼 程式碼如下:

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事件中指向滑鼠去往的那個元素
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn