需求

  1. 若文字长度不超过容器宽度,则不滚动, 反之滚动(复制一遍文字,让滚动无缝衔接)。
  2. 匀速滚动(运动时间 = 路程 / 速度)。
  3. 监听resize事件,结合防抖throttle,触发后重新计算是否需要滚动。

实现

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
63
64
65
66
67
68
69
70
71
72
<template>
<div>
<div class="notice" ref="container">
<p ref="notice">{{notice}}</p>
</div>
</div>
</template>
<script>
import { throttle } from '@/utils'
export default {
data () {
return {
defaultTxt: '测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试。。。。。测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试。。。。。测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试。。。。。测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试。。。。。测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试测试环境用于测试。。。。。',
notice: ''
}
},
mounted () {
this.getStyle()
window.addEventListener('resize', throttle(this.getStyle, 1000, true))
},
methods: {
getStyle () {
this.notice = this.defaultTxt
this.$nextTick(() => {
let containerW = this.$refs.container.clientWidth
let noticeW = this.$refs.notice.clientWidth
console.log(containerW, noticeW)
if (noticeW > containerW) {
this.notice = this.defaultTxt + this.defaultTxt
this.$refs.notice.className = 'run'
this.$refs.notice.style.animationDuration = noticeW / 100 + 's' // 匀速
} else {
this.notice = this.defaultTxt
this.$refs.notice.className = ''
this.$refs.notice.style.animationDuration = 0
}
})
}
},
destroyed () {
window.onresize = null
}
}
</script>
<style lang="scss" scoped>
.notice {
position: relative;
width: 100%;
overflow: hidden;
height: 30px;
line-height: 30px;
background: rgb(247, 225, 225);
color: #666;
@keyframes run {
from {
transform: translateX(0);
}
to {
transform: translateX(-50%);
}
}
p {
position: absolute;
top: 0;
left: 0;
white-space: nowrap;
}
.run {
animation: 20s run linear infinite;
}
}
</style>

附上防抖throttle代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export const throttle = (fn, delay = 1000, last = false) => {
let timer = null;
let start = new Date();
return function () {
last && timer && clearTimeout(timer);
let now = new Date();
let context = this;
let args = arguments;
if (now - start >= delay) {
fn.apply(context, args);
start = now;
} else {
if (last) { // 脱离事件后执行最后一次 // 一般用于触底加载之类 // 防止重复提交不需要执行最后一次
timer = setTimeout(() => {
fn.apply(context, args);
}, delay - (now - start));
}
}
}
}
感谢您的阅读,本文由 Astar 版权所有。如若转载,请注明出处:Astar(http://example.com/2021/12/12/%E4%BD%BF%E7%94%A8animation%E5%AE%9E%E7%8E%B0%E6%96%87%E5%AD%97%E6%97%A0%E9%99%90%E6%A8%AA%E5%90%91%E6%BB%9A%E5%8A%A8/
Array.prototype.fill()生成二维数组问题
MongoDB常用命令自查笔记