在手机上展示我们的标题的时候,我们当前的场景不允许出现两行,但是空间只有那么大,还要让用户看到完整的信息,所以采用超出滚动的方式来解决当前的问题。
原生的marquee标签中间包裹文字就可以滚动,但是显然不符合我们想要的。
通过vue实现文本超出滚动
<template>
<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>
</template>
<script>
export default {
name: 'marquee',
props: ['val'],
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)
}
}
</script>
<style scoped>
.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;
}
</style>
使用组件
//引入组件
import Marquee from './marquee'
//注册并使用
<Marquee :val=""></Marquee>
本文地址:https://www.zhuimengzhu.com/details/449.html
转载地址:blog.csdn.net/xj2wjtx/article/details/111224805
转载说明:转载时请在文首注明来源zhuimengzhu.com 及教程作者,并附本文链接。谢谢各位编辑同仁配合。zhuimengzhu 保留追究相应责任的权利。