2012-04-03 164 views
1

试图移动使用悬停一些div一类,这是我的标记:找到属于母公司jQuery中

<div class="item dark-grey"> 
    <div class="img"> 
     <img src="images/case-study-develop.jpg" width="174" height="59" alt="Case Study"> 
    </div> 
    <div class="triangle-container"> 
     <div class="triangle-border-light-blue"></div> 
     <div class="triangle-dark-grey"></div> 
    </div> 
    <div class="content light-blue"> 
     <h2><a href="#">Developing community work with the voluntary sector</a></h2> 
    </div> 
</div> 

这是我在用的那一刻,它工作正常,但我只想要悬停在内容div上,而不是整个项目div。

$(document).ready(function() { 
      $('.item').hover(function(e){ 
        $('.img', this).animate({height: "30px"},100); 
      },function(e){ 
        $('.img', this).animate({height: "58px"},100); 
      }); 
    }); 

我想如果我将鼠标悬停在.item。内容,然后让家长,并找到.IMG归属于母公司它的工作,但我不知道如果我这样做是正确的。

$('.item .content').hover(function(e){ 
       $(this).parents('.img').animate({height: "30px"},100); 
} 
+2

Downvote似乎苛刻。 – 2012-04-03 14:35:03

回答

2

你有什么将不会工作,因为.img不是.content的父母,它是兄弟姐妹。

您可以检查siblings().content()的:

$('.item .content').hover(
    function(e){ 
     $(this).siblings('.img').animate({ height: "30px" }, 100); 
    }, 
    //function... 
}); 

或者你也可以在DOM遍历高达.content父然后find('.img')

$('.item .content').hover(
    function(e){ 
     $(this).parent().find('.img').animate({ height: "30px" }, 100); 
    }, 
    //function... 
}); 

或者,如果你能保证structrue这些div永远不会改变,你可以使用prev()

$('.item .content').hover(
    function(e){ 
     $(this).prev().prev().animate({ height: "30px" }, 100); 
    }, 
    //function... 
}); 
1

这听起来像你想的:

$('.item .content').hover(function(e) { 
    $(this).closest('.item').find('.img').animate({height: "30px"}, 100); 
}, function(e) { 
    $(this).closest('.item').find('.img').animate({height: "58px"}, 100); 
}); 

这将观看悬停.content对象上,当悬停事件发生时,它会发现.item容器,然后找到在.img对象该容器并对其进行动画处理。

这里的关键之一是.closest(),它找到匹配给定选择器的第一个祖先,这对于找到特定的容器div非常有用。

1

<img />不是.item .content元素的父亲,因此您不能使用它。

您可以使用closest()导航到.item元素,然后从那里获取.img元素;

$(this).closest('.item').children('img').animate({height: "30px"},100); 

虽然,作为.img元素是你可以做的.item .content元素的兄弟姐妹;

$(this).siblings('.img').animate({height: "30px"},100); 

欲了解更多信息,请参阅siblings()closest()文档。

1
$(this).parent().find('.img') 

应该工作