onmouseout 有時會太過靈敏——當滑鼠移經元素內部的文字或子元素時就會觸發,導致功能顯示不正常。整理出三種解法供大家參考。
<script type="text/javascript">
function test(obj, e) {
if (e.currentTarget) {
if (e.relatedTarget != obj) {
if (obj != e.relatedTarget.parentNode) {
alert(1);
}
}
} else {
if (e.toElement != obj) {
if (obj != e.toElement.parentNode) {
alert(1);
}
}
}
}
</script>
<div onmouseout="test(this, event)" style="width:100px;height:100px;border:1px #666 solid">
<span style="margin:5px;width:100%;height:100%;border:1px #ff0000 solid">faddsf</span>
</div>
透過 contains 判斷滑鼠是否真的離開了元素範圍,模擬出標準的 mouseleave 行為:
var LeaveFunext = function (t, f) { for (var p in f) { t[p] = f[p]; } return t; };
var IE = '\v' == 'v';
var contains = function (wrap, child) {
if (IE) return wrap.contains(child);
while (child && typeof (child.parentNode) != "undefind") {
if (wrap == child) return true;
child = child.parentNode;
}
return false;
};
var LeaveFun = function (o) {
var _o = typeof o == "string" ? document.getElementById(o) : o;
return this == window ? new LeaveFun(_o) : LeaveFunext(_o, LeaveFun.prototype);
};
LeaveFun.prototype = {
mouseleave: function (fn) {
if (IE) {
this.attachEvent('onmouseleave', fn);
} else {
this.addEventListener('mouseout', function (e) {
tar = e.relatedTarget;
if (!contains(this, tar)) {
fn.call(this);
}
}, false);
}
return this;
}
};
// 呼叫
LeaveFun('share_customerdiv').mouseleave(function () {
document.getElementById('share_customerdiv').style.display = 'none';
});
<div style="z-index: 11;" onmouseout="this.style.display='none'" onmouseover="this.style.display='block'"> <b class="STYLE19">更多此人的...</b> <a class="STYLE8">留言板</a> <a class="STYLE8">好友</a> </div>
三種方式各有取捨:第一種靠判斷相關目標,第二種封裝性最好、能正確模擬 mouseleave,第三種最省事但在部分系統上會有輕微閃爍。