jquery animate background position

2019-01-03 06:09发布

I can't seem to get this working.

$('#product_family_options_dd').animate({
  height: '300px',
  width: '900px',
  backgroundPosition: '-20px 0px',          
},

The height and width animate but not the background.

12条回答
干净又极端
2楼-- · 2019-01-03 06:34

I guess it might be because it is expecting a single value?

taken from the animate page on jQuery:

Animation Properties and Values

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

查看更多
爷、活的狠高调
3楼-- · 2019-01-03 06:35
function getBackgroundPositionX(sel) {
    pos = $(sel).css('backgroundPosition').split(' ');
    return parseFloat(pos[0].substring(0, pos[0].length-2));
}

This returns [x] value. Length of number has no matter. Could be e.g. 9999 or 0.

查看更多
可以哭但决不认输i
4楼-- · 2019-01-03 06:37

You can change the image background position using setInterval method, see demo here: http://jquerydemo.com/demo/animate-background-image.aspx

查看更多
Emotional °昔
5楼-- · 2019-01-03 06:38

jQuery's animate function is not exclusively usable for directly animating properties of DOM-objects. You can also tween variables and use the step function to get the variables for every step of the tween.

For example, to animate a background-position from background-position(0px 0px) to background-position(100px 500px) you can do this:

$({temporary_x: 0, temporary_y: 0}).animate({temporary_x: 100, temporary_y: 500}, {
    duration: 1000,
    step: function() {
        var position = Math.round(this.temporary_x) + "px " + Math.round(this.temporary_y) + "px";
        $("#your_div").css("background-position",  position);
    }
});

Just make sure to not forget the this. inside the step function.

查看更多
相关推荐>>
6楼-- · 2019-01-03 06:42

You can also use math combination "-=" to move background

$(this).animate( {backgroundPositionX: "-=20px"} ,500);
查看更多
欢心
7楼-- · 2019-01-03 06:47

You don't need to use the background animate plugin if you just use separate values like this:

$('.pop').animate({
  'background-position-x': '10%',
  'background-position-y': '20%'
}, 10000, 'linear');
查看更多
登录 后发表回答