2014-01-07 18 views
-2

jQuery中是否有任何函數可以返回truefalse如果鼠標進入其子元素?檢測jQuery鼠標進入一個子元素?

我期待的東西我可以用這樣的:

if ($(this).mouseIsOnChild()) { 
    // mouse is on a child element 
} else { 
    // mouse leaved branch of HTML tree 
} 

courese中.mouseIsOnChild()功能不存在。然而。

+0

你也可以在你爲什麼需要做這樣的事情 – Alexander

+0

我想檢測,其中評論是鼠標離開時,實際元素來顯示和隱藏等元素。 – netdjw

回答

0

在事件處理器 - 您可以檢查是否e.targete是在事件處理函數傳遞參數)是觸發使用事件當前元素.is()

if($(this).children('div').is(e.target)){ 
// replacing $(this).children('div') with the children element selector 
}else{ 

} 

FIDDLE

如果你正在尋找一個特定的孩子,但任何孩子,你可以做這樣的事情

if($('>*',this).is(e.target)){ 
    // do something if it's children 
}else{ 

} 

FIDDLE

0

是的。存在mouseenter()mouseleave()事件。

利用這一點,我們可以構建一個數據結構,檢查如果鼠標是在兒童的區域:

$(function() { 
    var isIn = false; 
    $(target).children().mouseenter(function() {isIn = true;}); 
    $(target).children().mouseleave(function() {isIn = false;}); 

    var isMouseIn = function() { return isIn; }; 
}); 

現在,你的函數isMouseIn()返回true,如果鼠標是孩子裏面,否則爲false。

如果您想獲得幻想,您可以將自定義數據附加到target節點而不是全局變量。我將把這作爲一個鍛鍊的動機。

+0

如何告訴我這些函數鼠標是否在子元素上? – netdjw

+0

'$(this).children()。mouseenter()' – PaulProgrammer

1
//track hover state  
$('*').hover(function() { 
      $(this).data('hover', true); 
     }, function() { 
      $(this).data('hover', false); 
     }); 

//plugin to check whether mouse is on children 
$.fn.mouseIsOnChild = function() { 
    var ret = false; 
    $(this).children().each(function() { 
      ret = $(this).data('hover'); 
      return ret ? false : true; 
     }); 
    return ret; 
} 
+0

謝謝,這也是一個很好的例子 – netdjw

相關問題