2015-02-08 82 views
0

我想要处理多个HTML元素上的鼠标进入/离开事件。 我有多个HTML元素,我想在鼠标进入或离开这个特定的元素组时触发一个事件。注意:我不能在一个父div中“分组”这些元素。JQuery - 多个元素的鼠标离开事件

示例代码:http://jsfiddle.net/727g4c7h/1/

<div id="d1" style="width:100px; height:100px; background-color:red"></div> 
<div id="d2" style="width:100px; height:100px; background-color:blue"></div> 
<div style="width:100px; height:100px; background-color:green"></div> 
<div id="result">result</div> 

$(function(){ 
    $('#d1, #d2').mouseenter(function(){ 
      $('#result').html('enter ' + Math.random()); //random to distinguish subsequent events 
    }); 

    $('#d1, #d2').mouseleave(function(){ 
      $('#result').html('leave ' + + Math.random()); 
    }); 

}); 

当鼠标进入格#d1或#D2和叶#d1或#D2

+0

那么你的代码做错了什么? – 2015-02-08 09:41:26

+1

当你从红色移动到蓝色div时,事件被触发 - 这不应该做 – Igor 2015-02-08 09:50:21

+0

我很久没有跟jquery过,但是尝试调整div的位置和实际高度,例如if( !(position> $(“#d1”)。height())),如果这个位置,实际坐标不大于第一个div高度,则显示math.random,否则如果位置(坐标更大,那么不要做) – 2015-02-08 10:08:43

回答

4

利用代替IDS类简化一切,并用css事件应该被解雇属性,而不是内联的CSS清洁html。

根据上面的评论,我猜你不想在从一个div移动到另一个div时触发mouseleave,而只是在离开所有div时。使用e.toElement || e.relatedTarget添加来检查并限制代码的调用时间。

$(function(){ 
 
    $('.mouseWatch').mouseenter(function(){ 
 
      $('#result').html('enter ' + Math.random()); 
 
    }); 
 

 
    $('.mouseWatch').mouseleave(function(e){ 
 
      // get new element that is now hovered 
 
      var element = e.toElement || e.relatedTarget; 
 
      // only call our on leave code if the user's mouse left all mouseWatch divs 
 
      if(!$(element).hasClass('mouseWatch')){ 
 
      $('#result2').html('leave ' + + Math.random()); 
 
      } 
 
    }); 
 

 
});
.red{ 
 
    background-color:red; 
 
    } 
 
.blue{ 
 
    background-color:blue; 
 
    } 
 
.green{ 
 
    background-color:green; 
 
    } 
 

 
.mouseWatch{ 
 
    width:100px; 
 
    height:50px; 
 
    float:left; /*added to better fit the space on SO*/ 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="mouseWatch red"></div> 
 
<div class="mouseWatch blue"></div> 
 
<div class="mouseWatch green"></div><br><br><br><br> 
 
<div id="result">result</div><br> 
 
<div id="result2">result</div> (added second result div to better show leave vs enter)

相关问题