在原作者的基础上稍加改动,感觉更适用于有些内容太多只展示一行,但是又需要滑到元素区域内容开始滚动展示! 原创地址:https://blog.youkuaiyun.com/dkm123456/article/details/110954507?spm=1001.2014.3001.5501
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
.main{
width: 100%;
height: 30px;
background-color: red;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<div class="main" @mouseenter="startFn" @mouseleave="stopFn">
<h3>{{content}}</h3>
<!-- 本身可以当作组件来使用 -->
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
timer:null,
content:'',
startVal:'这个事件会在文档被滚动期间重复被触发,所以应当尽量保持事件处理程序的代码简单。' // 可以当作组件传进来的值
},
methods:{
startFn: function(){
//清除定时器,防止重复点击
clearInterval(this.timer);
this.timer = setInterval(()=>{
//this.content.substr(1) ==> 取到content第1位到结尾的内容(不包含第1位)
//this.content.substr(0,1) ==> 取到content的第1位
//将以上2个内容想连接赋值给 Content
this.content = this.content.substr(1) + this.content.substr(0,1);
},400);
},
stopFn: function(){
// 离开后重新回到最初的值
this.content = this.startVal
clearInterval(this.timer);//停止定时器
}
},
mounted(){
// 可以当作监听传入的值,如果有变化重新给content赋值
this.content = this.startVal
}
});
</script>
</html>