开发者

Changing EACH buttons background images with jquery

I would like to EACH button separately to change its background images as the user rollovers it.

As I have it by the moment, they are changing but BOTH buttons at the same time and that开发者_如何学C it's not what I would like them to behave.

Please could you help me?

Here is the fiddle: http://jsfiddle.net/Nb7LV/2/

Many thanks in advance!!! =D


You do not need the each(). Just use $(".button").hover()

And use this in the callback:

$(this).children('.btn-left').eq(0).toggleClass('btn-left-hover');


Your script changes every button because you put all of the toggles under the each(), which means all toggles apply when any of them trigger the hover event.

But you don't even need JavaScript / jQuery. Just make the following change in your CSS and remove your jQuery:

.button:hover .btn-left{
    background:url(../images/btn-left-hover.png);
}

.button:hover .btn-middle{
    background:url(../images/btn-middle-hover.png);
}

.button:hover .btn-right{
    background:url(../images/btn-right-hover.png);
}

Alternatively, you can make the following edit to your script. This will only update the spans that are children of your hovered element.

$(this).find('.btn-left').toggleClass('btn-left-hover');
$(this).find('.btn-middle').toggleClass('btn-middle-hover');
$(this).find('.btn-right').toggleClass('btn-right-hover');


Just specify that the context is this for each of your selectors:

$('.button').hover(function(){
    $('.btn-left', this).toggleClass('btn-left-hover');
    $('.btn-middle', this).toggleClass('btn-middle-hover');
    $('.btn-right', this).toggleClass('btn-right-hover');
});

I also removed the .each() since that's unnecessary (hover will be applied to each matching element anyways).

JSFiddle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜