开发者

Background-position +/- X pixels

开发者 https://www.devze.com 2023-04-07 01:17 出处:网络
How do I offset the background-position, let\'s s开发者_Python百科ay 20px, from its original position?

How do I offset the background-position, let's s开发者_Python百科ay 20px, from its original position?

Like:

$(".selector").animate("slow").css("backgroundPosition", "center -=20px");

(That obviously doesn't work... But how do I do this??)


jQuery by default does not animate backgrounds. There is this short code that can enable that. After you add it your code should work but first fix it like this:

$(".selector").animate({ "backgroundPosition": "center -=20px" },"slow");

Taken from:

http://snook.ca/archives/javascript/jquery-bg-image-animations

Demo:

http://snook.ca/technical/jquery-bg/


Animating CSS background-position works with standard jQuery .animate(), as in this example.

HTML

<p>Lorem ipsum</p>

CSS

p {
    height:50px;
    width:200px;
    background-image:url(http://lorempixum.com/200/50);
}

JavaScript

$('p').animate({'backgroundPosition':'-20px'}, 'slow');


You want to animate it or just change it?

You can change it by doing something like:

var newPos = parseFloat(($('.selector').css('backgroundPosition').replace('px', ''))+20) + "px";
$('.selector').css('backgroundPosition', newPos);
0

精彩评论

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

关注公众号