原理
復制1份需要無限滾動的列表,當滾動到第一個列表的結尾處(第二個列表的開始處時),立刻替換位移到初始位置(x=0)由於當時場景與剛開始的場景完全相同,就實現了無縫滾動
demo:
<template>
<div>
<div class="scroll-temp">
<div class="temp-box" ref="temp">
<div v-for="v in 5" :key="v + '1'" class="li">
{{ "name" + v }} 當前溫度:<span :class="v.ts">{{ v }}℃</span>
濕度:<span :class="v.hs">{{ v }}%</span>
</div>
<div v-for="v in 5" :key="v + '2'" class="li">
{{ "name" + v }} 當前溫度:<span :class="v.ts">{{ v }}℃</span>
濕度:<span :class="v.hs">{{ v }}%</span>
</div>
</div>
</div>
</div>
</template>
<script>
let x = 0;
export default {
data() {
return {
tempInterval: undefined
};
},
components: {},
computed: {},
destroyed() {
clearInterval(this.tempInterval);
},
mounted() {
this.tempInterval = setInterval(this.rollTemp, 50);
},
methods: {
rollTemp() {
let all = 0;
let count = this.$refs.temp.childElementCount;
for (let i = 0; i < count; i++) {
all += this.$refs.temp.children[i].offsetWidth;
}
let half = all >> 1;
if (x < 1 - half) {
x = 0;
}
x -= 2;
this.$refs.temp.style.transform = "translateX(" + x + "px)";
}
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss" rel="stylesheet/scss">
.scroll-temp {
background:black;
font-size: 20px;
top: 100px;
left: 480px;
width: 980px;
color: #fff;
height: 30px;
line-height: 30px;
overflow: hidden;
.temp-box {
white-space: nowrap;
.li {
display: inline;
height: 30px;
padding-right: 20px;
}
}
}
</style>
