需求
- 若文字长度不超过容器宽度,则不滚动, 反之滚动(复制一遍文字,让滚动无缝衔接)。
- 匀速滚动(运动时间 = 路程 / 速度)。
- 监听resize事件,结合防抖throttle,触发后重新计算是否需要滚动。
实现
<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代码
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));
}
}
}
}
本文介绍了一个需求,当文字长度超过容器宽度时,利用CSS3和JavaScript实现匀速无缝横向滚动效果。同时,通过监听resize事件并结合防抖函数throttle,确保在窗口大小变化时能自动调整滚动状态。
552

被折叠的 条评论
为什么被折叠?



