Changing only y pos of background image via Jquery

无人久伴 提交于 2019-11-29 10:55:00

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

Maybe like this:

var bg = $('#element').css('backgroundPosition').split(' ');
bg[1] = '-200px';

$('#element').css('backgroundPosition', bg.join(' '));

As the background-position is always stored in the order horizontal vertical this should work as the second array value is always the vertical value.

Though this may only work with one element. With multiple elements you may have to use a loop.

I decided there is no simple solution and find a way out at the end. If somebody needs this below script works with no problem.

$('.bt_first,.bt_sec,.bt_third').hover(
function(){
    var id = $(this).closest('a').attr('id');
    var bg1 = $('#'+id+' > .bt_first').css('background-position').split(' ');
    var bg2 = $('#'+id+' > .bt_sec').css('background-position').split(' ');
    var bg3 = $('#'+id+' > .bt_third').css('background-position').split(' ');
    bg1[1] = '-134px';
    bg2[1] = '-134px';
    bg3[1] = '-134px';
    $('#'+id+' > .bt_first').css('background-position', bg1.join(' '));
    $('#'+id+' > .bt_sec').css('background-position', bg2.join(' '));
    $('#'+id+' > .bt_third').css('background-position', bg3.join(' '));
},
function(){
    var id = $(this).closest('a').attr('id');
    var bg1 = $('#'+id+' > .bt_first').css('background-position').split(' ');
    var bg2 = $('#'+id+' > .bt_sec').css('background-position').split(' ');
    var bg3 = $('#'+id+' > .bt_third').css('background-position').split(' ');
    bg1[1] = '-110px';
    bg2[1] = '-110px';
    bg3[1] = '-110px';
    $('#'+id+' > .bt_first').css('background-position', bg1.join(' '));
    $('#'+id+' > .bt_sec').css('background-position', bg2.join(' '));
    $('#'+id+' > .bt_third').css('background-position', bg3.join(' '));
}
);

You should have an "a" tag with an "id" as parent of all elements and also these elements must be first childs. Otherwise modify script.

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!