2015-02-08 77 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)

相關問題