2015-02-24 59 views
0

如何讓Jquery代碼只選擇主div(.post)? 它也影響它的孩子,內部div。JQuery選擇器影響其子

我使用這個:

$(document).ready(function() { 
$(".post") 
    .mouseover(function() { 
     $(this).animate({ 
      height: 180, 
      width: 160 
     }, 200, function() { 
      // Animation complete. 
     }); 
    }) 
    .mouseout(function() { 
     $(this).animate({ 
      height: 150, 
      width: 150 
     }, 200, function() { 
      // Animation complete. 
     }); 
    }); 

});

下面的代碼:http://jsfiddle.net/q5g4xrqf/

+0

不適合我(火狐37)瀏覽器的問題可能影響內部元件? – atmd 2015-02-24 16:45:47

+1

當您將鼠標移動到橙色div上時,它會增長,好! 但是,當你在橙色裏面滾過黑色時,它會縮小並再次增長...:/ – 2015-02-24 16:49:18

+0

所以,我更新了這裏:http://jsfiddle.net/q5g4xrqf/5/ 我想要一個文本出現在橙色div的頂部,但我不希望黑色div移動。什麼是最好的解決方案? 這是它是如何:http://jsfiddle.net/q5g4xrqf/6/ – 2015-02-25 15:53:50

回答

0

切換您.mouseover().mouseout().mouseenter().mouseleave()

$(document).ready(function() { 
    $(".post") 
     .mouseenter(function() { 
     $(this).animate({ 
      height: 180, 
      width: 160 
     }, 200, function() { 
      // Animation complete. 
     }); 
    }) 
     .mouseleave(function() { 
     $(this).animate({ 
      height: 150, 
      width: 150 
     }, 200, function() { 
      // Animation complete. 
     }); 
    }); 
}); 

jsFiddle example

從文檔:

mouseenter/mouseleave事件與鼠標懸停/鼠標懸停事件的處理方式不同,它處理事件冒泡的方式爲 。 mouseenter/mouseleave事件只在鼠標進入/離開它綁定的元素時觸發其處理程序,而不是後代。

另請注意,您也可以使用.hover()函數調用mouseenter和mouseleave來縮短代碼。

+1

它的工作!謝謝! 我必須等6分鐘才能在這裏接受...:/ 15代表做出積極評價 – 2015-02-24 16:52:44

0

mouseovermouseout正在這裏做它們的功能。使用hover來抵消這種影響。

WORKING DEMO

$(document).ready(function() { 
    $('.post').hover(function() { 
     $(this).animate({ 
      height: 180, 
      width: 160 
     }, 200, function() { 
      // Animation complete. 
     }); 
    }, function() { 
     $(this).animate({ 
      height: 150, 
      width: 150 
     }, 200, function() { 
      // Animation complete. 
     }); 
    }); 
}); 
0

解決方案:使用mouseentermouseleave

**原因:*如上所述由jQuery docmouseovermouseout氣泡成子元素:

mouseover也會在指針移動到子元素時觸發,而mouseenter僅當指針移動到綁定元素時觸發。

對於mouseoutmouseleave也是一樣的。

小提琴:http://jsfiddle.net/q5g4xrqf/3/