jQuery Animated Background Position

jQuery animate() 함수 backgroundPosition 사용

배경이미지의 background-position 값 위치를 jQuery로 동적으로 제어하는 방법을 알아보자.

jQuery v1.4.3 이상 버전부터는 animate() 함수에서 backgroundPosition 속성을 지원하지 않는다.
따라서 속성값을 background-position-x, background-position-y 로 변경하여 사용해야 된다.
(참고) 하지만 1.3.x 이하 버전에서는 이 속성을 지원하지 않는다.

1.3.x 이하 버전

1
$(this).animate({backgroundPosition: '20px 30px'});

1.4.0 이상 버전

1
$(this).animate({'background-position-x': '20px', 'background-position-x': '30px'});

크로스브라우징 이슈

animated() 의 background-position-xbackground-position-y로 구현시 IE11 이하 브라우저에서는 지원이 되지 않는다.
브라우저 파면화를 고려한다면 다음과 같이 플러그인으로 구현된 아래 코드를 활용하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$.fn.animateBgPosition = function(x, y, speed) {
var pos = this.css('background-position').split(' ');

this.x = parseInt(pos[0]) || 0;
this.y = parseInt(pos[1]) || 0;

$.Animation(this, {
x: x,
y: y
}, {
duration: speed
}).progress(function(e) {
this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px');
});

return this;
};

$({{@selector}}).on({
mouseenter: function() {
$(this).stop(true,true).animateBgPosition('0', 0, 400);
},
mouseleave: function() {
$(this).stop(true,true).animateBgPosition('-400px', 0, 400);
}
});

참조

공유하기