2015-02-24 58 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/