JavaScript onmouseout 事件触发过于灵敏的三种解决方案

作者:窗边听雨时间:2026-10-25 08:18:33浏览:257

本文针对JavaScript中onmouseout事件在鼠标经过层内子元素时容易误触发的问题,提供了三种解决方案。第一种通过判断relatedTarget和toElement排除子节点;第二种封装LeaveFun类利用contains方法兼容IE;第三种采用简单的display属性切换,虽可能有轻微闪烁但实现最简。

在使用JavaScript处理鼠标事件时,开发者常发现onmouseout事件的触发机制过于敏感。当鼠标指针从容器移动到其内部的文字链接或子元素时,会立即触发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>

方案二:封装LeaveFun类兼容IE

第二种方案:封装LeaveFun类,利用contains方法兼容IE浏览器。


代码如下:

 
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>
<a class="STYLE8"></a>
</div>
作者最新文章