<!-- 跑马灯组件 -->
<div class="marquee-wrap" ref="marquee-wrap">
<div class="scroll" ref="scroll">
<p class="marquee">{{text}}</p>
<p class="copy" ref="copy"></p>
</div>
<p class="getWidth" ref="getWidth">{{text}}</p>
</div>
js:功能
如果是要滚动数组里的文字,可以使用mounted方法,否则可以不写
export default {
name: 'marquee',
data () {
return {
timer: null,
text: ''
}
},
created () {
let timer = setTimeout(() => {
this.move()
clearTimeout(timer)
}, 1000)
},
mounted () {
for (let item of this.val) {
this.text += item
}
},
methods: {
move () {
let maxWidth = this.$refs['marquee-wrap'].clientWidth
let width = this.$refs['getWidth'].scrollWidth
if (width <= maxWidth) return
let scroll = this.$refs['scroll']
let copy = this.$refs['copy']
copy.innerText = this.text
let distance = 0
this.timer = setInterval(() => {
distance -= 1
if (-distance >= width) {
distance = 16
}
scroll.style.transform = 'translateX(' + distance + 'px)'
}, 20)
}
},
beforeDestroy () {
clearInterval(this.timer)
}
}
CSS:样式调整
.marquee-wrap {
width: 100%;
overflow: hidden;
position: relative;
}
.marquee{
margin-right: 0.16rem;
}
p {
word-break:keep-all;
white-space: nowrap;
font-size: 0.28rem;
}
.scroll {
display: flex;
}
.getWidth {
word-break:keep-all;
white-space:nowrap;
position: absolute;
opacity: 0;
top: 0;
}
第二种:
HTML:
<!-- 滚动通知 -->
<div class="container">
<div class="text" style="color:rgb(255,121,1);font-size:16px; "><i class="el-icon-warning-outline" style="font-weight: 500;" /> </div>
</div>
CSS:
.container{
display: flex;
overflow: hidden;
text-overflow: ellipsis;
width: 100%;
}
.text{
padding: 0 5px;
white-space:nowrap;
}
JS:
move(zoumadeng){
const container = document.querySelector(".container"); // 容器元素
const textNode = document.querySelector(".container > .text"); // 文字元素
textNode.innerHTML= textNode.innerHTML + zoumadeng
// container.appendChild(textNode.cloneNode(true)); // 复制元素到后方
const textWidth = textNode.offsetWidth; // 获取文字元素宽度
let count = container.offsetWidth; // 初始化向左偏移为容器大小
const loop = () => {
if(count <= -textWidth) { // 如果文字偏移超出一个文字元素的宽度则复原
textNode.style["margin-left"] = 0;
count = container.offsetWidth
}
textNode.style["margin-left"] = `${count--}px`; // 继续向左移动
window.requestAnimationFrame(() => loop()); // 动画递归调用
}
window.requestAnimationFrame(() => loop()); // 启动动画
}
补充:
若是想实现动态获取字数,即一行文本滚动结束后紧接着继续出现,无缝链接
getLenPx(str, font_size) {
var str_leng = str.replace(/[^\x00-\xff]/gi, 'aa').length;
return ((str_leng * font_size) / 2 ) + 5
},
说明:getLenPx(str, font_size) str:文本内容 ;ont_size:文本字号;即:this.getLenPx("测试滚动文字",16)