5

我在网格上有 9 个项目,我希望所有项目在每个项目上都有 0.5 的不透明度,并且只有当将鼠标悬停在 div/item 和里面的所有东西都有 1.0 的不透明度时。

这是JS

$('.gallery-single').css({ opacity: 0.5 });

$('.gallery-single a').mouseover(function(){
    $('.gallery-single-title', this).css('display', 'block');
        $('.gallery-single', this).css({ opacity: 1 });
});
$('.gallery-single a').mouseout(function(){
    $('.gallery-single-title', this).css('display', 'none');
        $('.gallery-single', this).css({ opacity: 0.5 });
}); 

HTML

<div class="gallery-single">
<a href="#" title="">
<div class="gallery-single-title hide">Some text goes here</div>
<div class="gallery-single-img"><img src="http://img.youtube.com/vi/code/0.jpg" width="300" height="200" /></div>
</a>
</div>

加载时所有项目的不透明度为 0.5,但聚焦时不透明度不会更改。我在这里做错了什么?

4

2 回答 2

6

尝试这个:

$('.gallery-single a').hover(function(){
    $(this).closest('.gallery-single-title').css('display', 'block');
        $(this).closest('.gallery-single').css({ opacity: 1 });
},
function(){
    $(this).closest('.gallery-single-title').css('display', 'none');
        $(this).closest('.gallery-single').css({ opacity: 0.5 });
}); 

工作示例

于 2011-06-08T05:19:12.727 回答
1

问题是它.gallery-single是锚的祖先(即它在锚之外)。该$(selector, this)格式 this. 相反,使用.closest()

$(this).closest('.gallery-single').css(...);

旁注:jQuery 给出了这个警告mouseover(也适用于mouseout):

由于事件冒泡,这种事件类型会引起很多麻烦。例如,在本例中,当鼠标指针移到 Inner 元素上时,将向该元素发送 mouseover 事件,然后滴流到 Outer。这会在不合时宜的时候触发我们绑定的鼠标悬停处理程序。请参阅 .mouseenter() 的讨论以获取有用的替代方法。

您应该使用mouseenter(and mouseleave) 代替(或hover()方便地结合两者的功能)。

于 2011-06-08T05:22:10.090 回答