<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div class="box-outer">
<div class="before" v-show="isShow"></div>
<div class="after" v-show="isShow"></div>
<div
ref="sbox"
class="box vue-loop-scroll-box"
@mouseenter="stopScroll"
@mouseleave="leaveScroll"
>
<div ref="sitem1" class="vue-loop-scroll-item1">
<span>
111111111111111111
</span>
<span>
2222222
</span>
<span>
3333333
</span>
</div>
<div class="vue-loop-scroll-item2"></div>
</div>
</div>
</div>
</body>
</html>
<style>
.box-outer {
position: relative;
width: 500px;
overflow: hidden;
white-space: nowrap;
background-color: #e5e5e5;
}
.box {
position: relative;
overflow: hidden;
white-space: nowrap;
}
.box div{display: inline-block;}
.box-outer .before {
z-index: 1;
position: absolute;
left: 0;
top: 0;
bottom: 0;
content: "";
width: 100px;
background: linear-gradient(
to right,
rgba(255, 255, 255, 1),
rgba(255, 255, 255, 0.1)
);
}
.box-outer .after {
z-index: 1;
position: absolute;
right: 0;
top: 0;
bottom: 0;
content: "";
width: 100px;
background: linear-gradient(
to right,
rgba(255, 255, 255, 0.1),
rgba(255, 255, 255, 1)
);
}
ul {
display: inline-block;
}
</style>
<script>
var app = new Vue({
el: "#app",
data: {
speed: 50,
index: 0,
isShow: false,
},
mounted() {
this.startScroll();
},
methods: {
startScroll() {
this.$nextTick((res) => {
var sbox = document.getElementsByClassName("vue-loop-scroll-box")[
this.index
];
var sitem1 = document.getElementsByClassName("vue-loop-scroll-item1")[
this.index
];
if (this.$refs.sbox.offsetWidth > this.$refs.sitem1.offsetWidth) {
this.isShow = false;
return;
}
this.isShow = true;
var sitem2 = document.getElementsByClassName("vue-loop-scroll-item2")[
this.index
];
sitem2.innerHTML = sitem1.innerHTML;
var that = this;
this.timer1 = setInterval(function () {
that.scrollLeft(sbox, sitem1);
}, this.speed);
});
},
scrollLeft(sbox, sitem1) {
if (sbox.scrollLeft >= sitem1.offsetWidth) {
sbox.scrollLeft = 0;
} else {
sbox.scrollLeft++;
}
},
stopScroll() {
clearInterval(this.timer1);
},
leaveScroll() {
this.startScroll();
},
},
});
</script>