Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

css - Changing only y pos of background image via Jquery

I want to change button's background image y position with hover function. Is there a simple way of keeping xpos or should I get position first, split it and use again with $.css() again.

I should change all 3 span's background position if somebody hover's any of them. So bt_first:hover not seems usable.

Here is my usage. I wrote #should stay same# to place that I don't want to change value of xpos:

$('.bt_first,.bt_sec,.bt_third').hover(function(){
        $('.bt_first,.bt_sec,.bt_third').css({'background-position':'#should stay same# -150px'})
},function(){
        $('.bt_first,.bt_sec,.bt_third').css({'background-position':'#should stay same# -110px'});
});

Here is my html.:

<div><a id="add_comment_btn"><span class="bt_first comments_t"><span>&nbsp;</span></span><span class="bt_sec">&nbsp;</span><span class="bt_third">Comments</span></a></div>

And css:

.bt_first,.bt_sec,.bt_third,.logout_t,.comments_t span {
    background: url('img/toolbar_bckrnd.png') no-repeat;
}
.bt_first {
    background-position: left -110px;
    display: inline-block;
    height: 24px;
    width: 15px;
}
.bt_sec {
    background-position: -149px -110px;
    display: inline-block;
    height: 24px;
    width: 2px;
}
.bt_third {
    background-position: right -110px;
    display: inline-block;
    height: 24px;
    padding: 0 10px;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should work:

$('#add_comment_btn').hover(function(e) {
    var s = e.type == 'mouseenter' ? '-134px' : '-110px';        
    $(this).children().css('background-position', function(i,v) {
        return v.replace(/-?d+px$/, s);
    });
});

This applies to the #add_comment_btn anchor. If you have multiple anchors, just use a class selector to select them all.

btw the above code is basically the same as the code that you posted in your answer. I just got rid of the redundancy.


btw if you don't want to add classes to the anchors, you can select them like so:

$('.bt_first, .bt_sec, .bt_third').parent().hover( .... the above code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...