1、新建一個名爲marquee.vue的子組件,代碼如下
<template>
<div class="scrollText" ref="outer">
<div class="st-inner" :class="{'st-scrolling': needToScroll}">
<span class="st-section" ref="inner">{{text}}</span>
<span class="st-section" v-if="needToScroll">{{text}}</span>
<!-- 加兩條是爲了滾動的時候實現無縫銜接 -->
</div>
</div>
</template>
<script>
export default {
data () {
return {
needToScroll: false,
text: ''
}
},
mounted () {
this.startCheck()
},
beforeDestroy () {
this.stopCheck()
},
methods: {
// 檢查當前元素是否需要滾動
check () {
this.setText()
this.$nextTick(() => {
let flag = this.isOverflow()
this.needToScroll = flag
})
},
// 判斷子元素寬度是否大於父元素寬度,超出則需要滾動,否則不滾動
isOverflow () {
let outer = this.$refs.outer
let inner = this.$refs.inner
let outerWidth = this.getWidth(outer)
let innerWidth = this.getWidth(inner)
return innerWidth > outerWidth
},
// 獲取元素寬度
getWidth (el) {
let { width } = el.getBoundingClientRect()
return width
},
// 獲取到父組件傳過來的內容復傳給this.text
setText () {
this.text =
(this.$slots.default &&
this.$slots.default.reduce((res, it) => res + it.text, '')) ||
''
},
// 增加定時器,隔一秒check一次
startCheck () {
this._checkTimer = setInterval(this.check, 1000)
this.check()
},
// 關閉定時器
stopCheck () {
clearInterval(this._checkTimer)
}
}
}
</script>
<style scoped>
.scrollText {
overflow: hidden;
white-space: nowrap;
}
.st-inner {
display: inline-block;
}
.st-scrolling .st-section {
padding: 0 30px;
}
/* 向左勻速滾動動畫 */
.st-scrolling {
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% {
transform: translate3d(0%, 0, 0);
}
100% {
transform: translate3d(-50%, 0, 0);
}
}
</style>
2、在父組件引入:
<div class="scroll_box"><marquee> 我是一個跑馬燈跑馬燈跑馬燈跑馬燈跑馬燈....... </marquee></div><script>
import marquee from './marquee.vue'
export default {
components: {
marquee
},
}
</script>
//這裏設置的寬度就是文字長度超過30px後就自動滾動 <style scoped> .scroll_box { width: 30px; } </style>