开发者

Changing Opacity with jQuery

I have 9 items on a grid, I want all items to have 0.5 opacity on every item and only when hovered over should the div/item and everything inside have 1.0 opacicty.

Here is the 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>

All items are at opacity 0.5 when loaded but opacities are not changed when focused. Wh开发者_JAVA技巧at am I doing wrong here?


Try this:

$('.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 });
}); 

Working example.


The problem is that .gallery-single is an ancestor of the anchor (i.e. it's outside the anchor). The $(selector, this) format looks for the selector within this. Instead, use .closest():

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

Sidenote: jQuery gives this warning about mouseover (also applies to mouseout):

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.

You should use mouseenter (and mouseleave) instead (or the hover() function which conveniently combines the two).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜