开发者

Getting a CSS value from $(this) in jQuery

So I have working code that animates a BG image via a plugin. This is a general solution though where each element in the class has the same BG image; I'm using a sprite with a unique image for each column of my navigation bar. THe code is thusly:

$('#nav a')
.mouseover(function(){
    $(t开发者_StackOverflow中文版his).stop().animate(
        {backgroundPosition:"(0 -250px)"}, 
        {duration:500})
    })
.mouseout(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 0)"}, 
        {duration:500})
    })

This works great, so I can set a Y-offset for each element, but each link has it's own x-offset that won't change/be animated at all. Example CSS:

li.downloads a {
    background:url(img/navsprite.png) repeat -318px -9px;
}

I want to roll the -318px -9px to something like -318px 200px, but for another element I'd want to change -482px -9px to -482px 200px. Only the Y-offset should change, but I don't know the syntax of jQuery well enough to pull that value from the CSS of $(this) element and put it into the animate parameters. Thanks!


You can get the background position like this:

$(this).css("background-position");

You can get both values in an array like this:

var bgpos = $(this).css("background-position").split(" ");

Which allows you to access both values with bgpos[0] and bgpos[1].


There is a css property background-position-x. This is only available in IE however, so is probably not a valid solution for your problem.
jQuery does support relative animations by specifying f.e. +=50px;
No idea if it works, but you could try the following code:

$('#nav a')
.mouseover(function(){
    $(this).stop().animate(
        {backgroundPosition:"(+=0 -250px)"}, 
        {duration:500})
    })
.mouseout(function(){
    $(this).stop().animate(
        {backgroundPosition:"(+=0 0)"}, 
        {duration:500})
    })


jQuery.fn.getBackgroundxPosition = function(val) {
    var position = $(this).css('background-position');
    var position_array=val.split(' ');
    var x_pos = position_array[0];

    if(typeof(position) === 'undefined'){ //IE fix
        x_pos = $(this).css('background-position-x');
    }
return x_pos;
};

I think this will work (not tested)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜