仅使用相同的类jquery悬停在1个元素上

时间:2011-12-29 17:02:32

标签: jquery jquery-selectors hover css-selectors

我在jquery中有这段代码:

$(".pun").hover(function() {
 $(".guns").show(0);        
});

我的HTML

<div class="pun">
<div class="guns">gun 1</div>
</div>
<div class="pun">
<div class="guns">gun 2</div>
</div>
<div class="pun">
<div class="guns">gun 3</div>
</div>

我的css

.pun {
display:visible
}

.guns {
display:none
}

我想悬停操作只显示悬停的项目。现在,如果你做悬停显示每个div枪。

6 个答案:

答案 0 :(得分:4)

要仅显示您正在悬停的guns div内的pun div,请使用find函数

$(".pun").hover(function() {
   $(this).find(".guns").show(0);        
});

或为您的选择器提供上下文

$(".pun").hover(function() {
   $(".guns", this).show(0);        
});

此外,show的默认设置不会执行任何动画,因此您只需.show(0);替换show();

答案 1 :(得分:3)

仅使用CSS更容易实现:

div.pun div.guns {
    display: none;
}

div.pun:hover div.guns {
    display: block;
}

顺便说一下,visible不是display属性的有效值。而且,你错过了hover()的第二个参数(如果你坚持使用jQuery)。您可能应该hide()第二个函数中的.guns,或者如果您只想展示它们(并且从不隐藏它们),您可以使用mouseover()代替hover()。< / p>

答案 2 :(得分:1)

更改

$(".guns").show(0);

$(".guns", this).show(0);

这将仅在悬停元素的上下文中选择'.guns'。 (jsFiddle

答案 3 :(得分:0)

您可以通过ID识别它们,或者类似的东西应该可以工作(未经测试):

$(".pun").hover(function() {
    $(this).children(".guns:first").show(0);        
});

答案 4 :(得分:0)

进行子选择

$(".pun").hover(function() {
    $(this).children(".guns").show(0);        
});

答案 5 :(得分:0)

在悬停时,有两个events有界,mouseovermouseout。您可能希望将其隐藏在mouseout

$(".pun").hover(function() {
   $(this).children(".guns").show(100);        
},function(){
   $(this).children(".guns").hide(100);
});