CSS属性background-position-y实现动画
background-position-y
属性用于设置初始状态时背景图片在垂直方向的位置,这个位置相对于通过background-origin
定义的背景层原点进行定位,详见MDN 文档 (opens new window)。
今天要将的是如何利用background-position-y
属性实现简单的动画。
效果如下
class animate {
constructor(dom) {
this.element = dom;
this.timer_over = null;
this.timer_leave = null;
this.period = 30;
this.step = 128;
this.imgLength = -3228;
this.init();
}
init() {
this.element.addEventListener("mouseover", () => {
this.over();
});
this.element.addEventListener("mouseleave", () => {
this.leave();
});
}
over() {
if (this.timer_leave) {
clearTimeout(this.timer_leave);
}
this.timer_over = setInterval(
((step) => {
const positionYValue = this.getPositionY();
if (positionYValue > this.imgLength) {
this.element.style.backgroundPositionY = `${
positionYValue - this.step
}px`;
}
}).bind(this),
this.period
);
}
leave() {
if (this.timer_over) {
clearTimeout(this.timer_over);
}
this.timer_leave = setInterval(
(() => {
const positionYValue = this.getPositionY();
if (positionYValue != 0) {
this.element.style.backgroundPositionY = `${
positionYValue + this.step
}px`;
}
}).bind(this),
this.period
);
}
getPositionY() {
const styles = window.getComputedStyle(this.element);
const backgroundPositionY = styles.getPropertyValue(
"background-position-y"
);
const positionYValue = parseFloat(backgroundPositionY);
return positionYValue;
}
}
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
示例中定义了一个animate
类,通过addEventListener
监听鼠标的mousemove
和mouseleave
,从而改变background-position-y
的值;每项的背景图都是一个长图,长度为 128px * n, 步长step
设为 128px,从视觉效果上就形成了动画
编辑 (opens new window)
上次更新: 2024/05/24, 03:31:26