jquery mouseenter不适用于特定的div

时间:2015-12-19 08:29:54

标签: javascript jquery

Click here to view the demo.

这是代码

jQuery(document).ready(function($) {
  $(".works").mouseenter(function(e) {

        $( ".img_details" ).stop().animate({ 'bottom':'5%', 'opacity':'1'},500);
        e.preventDefault();
    });

    $( ".works").mouseleave(function(e) {

        $( ".img_details" ).stop().animate({ 'bottom':'100%', 'opacity':'0'},500);
        e.preventDefault();
    });

})(jQuery);

有两个带有班级名称的div" works"它拥有一个具有类名" img_details"的div。如果鼠标指针进入第一个div" img_details"也加载两个div。我想加载一次特定的div。我错过了什么?

3 个答案:

答案 0 :(得分:3)

您应该使用thisthis将指向当前对象,此处它将是当前悬停的.works,然后您会在{{{}}内找到特定的.img_details 1}}并仅为该元素设置动画。

this

Plunker

答案 1 :(得分:2)

请使用内容this

jQuery(document).ready(function($) {
  $(".works").mouseenter(function(e) {
    $(this).find(".img_details").stop().animate({
      'bottom': '5%',
      'opacity': '1'
    }, 500);
    e.preventDefault();
  });
  $(".works").mouseleave(function(e) {
    $(this).find(".img_details").stop().animate({
      'bottom': '100%',
      'opacity': '0'
    }, 500);
    e.preventDefault();
  });
})(jQuery);

原因:当您再次提供.works时,它会定位到文档中的每个.works。但是当您在回调函数中提供this 时,它仅指向<div>发生mouseenter的当前:)。这是jQuery的所有新手所犯的常见错误。 my $doc = XML::LibXML->load_xml(IO => \*STDIN); # or stream or file.. foreach my $node ($doc->documentElement()->findnodes("/path/to/your/element/text/reference")) { $node->parentNode()->appendText(yourLookupMethod($node->getAttribute("value")); $node->unbindNode(); } $doc->toFH(\*STDOUT, 0); # or stream or file...

输出:http://plnkr.co/edit/bKc00tEebxs9TAONBid4?p=preview

答案 2 :(得分:2)

( ".img_details" )将选择所有div个班级img_details。您应该在img_details下找到works并在其上使用动画,如下所示。

$(".works").mouseenter(function(e) {    
    $(this).find( ".img_details" ).stop().animate({ 'bottom':'5%', 'opacity':'1'},500);
    e.preventDefault();
});

$( ".works").mouseleave(function(e) {
    $(this).find( ".img_details" ).stop().animate({ 'bottom':'100%', 'opacity':'0'},500);
    e.preventDefault();
});

Plunker:http://plnkr.co/edit/HO7PuyfFwNZj4rpWJwU4?p=preview