vue 跑马灯顶部显示轮播效果
gif动画展示
在线预览
实现原理
使用定时器setInterval对元素的left进行间隔操作,逐渐减小,实现从右到左的移动。
mouseover时对定时器停止,mouseout时重新启动定时器。
由于移动元素需要加点击事件,所以使用了v-html指令,如不需要,请换成v-text
demo代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跑马灯效果</title>
<script src="https://cdn.bootcss.com/vue/2.5.15/vue.min.js"></script>
<style>
body,
p {
margin: 0;
}
.marBox {
background-color: antiquewhite;
width: 100%;
height: 30px;
line-height: 30px;
}
.marBox__child {
width: 100%;
height: 30px;
line-height: 30px;
position: absolute;
top: 0;
}
</style>
</head>
<body>
<!--容器-->
<div id="app">
<div @mouseover="stop" @mouseout="start" class="marBox">
<p class="marBox__child" :style="styles" v-html="msgStr"></p>
</div>
</div>
<script>
// 创建一个vue实例
var vm = new Vue({
el: '#app', // 绑定id为appid容器
data: {
// 通知信息
msg: [
{
txt:"获取浏览器的宽度",
link:"https://haley1688.gitee.io/toolshaley/pages/checkBrowser.html"
},
{
txt:"Haley的博客",
link:"https://blog.csdn.net/weixin_42708208"
},
{
txt:"百度",
link:"http://www.baidu.com"
},
{
txt:"颜色模式转换",
link:"https://haley1688.gitee.io/toolshaley/pages/colorTransformation.html"
},
],
timer: null,
speed: 100, //速度,数字越大,速度越慢
left: 2000, //默认起始位置
step: 5, //每步移动的距离
},
mounted() {
this.start();
},
methods: {
// 启动
start() {
this.timer = setInterval(() => { //定时任务
// console.log(this.left, -this.msgStr.length * 10)
if (this.left < -this.msgStr.length * 10) {
this.left = this.screenWidth
} else {
this.left -= this.step
}
// console.log(this.left)
}, this.speed);
},
// 停止
stop() {
clearInterval(this.timer);
}
},
computed: {
// 获取屏幕宽度
screenWidth() {
return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
},
// 将通知数组拼接为字符串,
msgStr() {
let arr=this.msg.map(item=>{
return `<a href="${item.link}">${item.txt}</a>`
})
return "<b>通告:</b>" + arr.join(Array(30).join(' '))
},
// 移动left值
styles() {
return {
'left': this.left + 'px'
}
}
},
beforeDestroy() {
this.stop()
}
})
</script>
</body>
</html>