1.
可以通过改变元素的marginLeft值和计时器来实现滚动
代码实现如下:
<template><divid="box"ref="box"><divclass="marquee-box"ref="marquee"="menter"="mleave"><pref="cmdlist"id="pWidth"><imgstyle="width: 12px;height: 12px"src="../assets/logo.png"alt="">这是一条公告这是一条公告这是一条公告</p></div></div></template>
exportdefault { name: 'HelloWorld', data () { return { value: 0, timer: '',//计时器pwidth:0,//公告文本的宽度windowWidth:document.documentElement.clientWidth,// 设备屏幕的宽度 } }, mounted() { letelement=this.$refs.cmdlist; this.pwidth=document.defaultView.getComputedStyle(element,'').width.split('px'); this.timer=setInterval(this.clickCommend, 20); }, watch:{ value(newValue, oldValue) { letallWidth=parseInt(this.windowWidth)+parseInt(this.pwidth[0]); if(newValue<=-allWidth){ this.$refs.cmdlist.style.marginLeft=this.windowWidth+"px"; this.value=0; } }, }, methods:{ clickCommend(e) { let_this=this; this.$nextTick(() => { this.value-=1; this.$refs.cmdlist.style.marginLeft=_this.windowWidth+this.value+"px"; }); }, menter(){ clearInterval(this.timer); }, mleave(){ this.timer=setInterval(this.clickCommend, 20); }, }, beforeDestroy() { clearInterval(this.timer); } }
css代码:
<stylescoped>#box { width: 100%; height: 50px; margin-top: 50px; position: relative; } .marquee-box { position: relative; width: 100%; height: 100%; overflow:auto; background-color: #f8f8f8; } #pWidth{ width: 100%; height: 50px; padding: 0; margin: 0; line-height: 50px; display: block; word-break: keep-all; white-space: nowrap; overflow:hidden; font-family: 微软雅黑; fontSize:14px; background-color: #f8f8f8} ::-webkit-scrollbar { width: 0!important; } ::-webkit-scrollbar { width: 0!important;height: 0; } </style>
2.也可以通过改变元素的left值。计时器来实现滚动
代码如下只需修改css和js代码
mounted() { // let element = this.$refs.cmdlist;// this.pwidth = document.defaultView.getComputedStyle(element,'').width.split('px');this.timer=setInterval(this.clickCommend, 20); }, watch:{ value(newValue, oldValue) { // let allWidth= parseInt(this.windowWidth)+parseInt(this.pwidth[0]);letallWidth=parseInt(this.windowWidth)+document.getElementById('pWidth').offsetWidth; if(newValue<=-allWidth){ // this.$refs.cmdlist.style.marginLeft = this.windowWidth+"px";this.$refs.cmdlist.style.left="100%"; this.value=0; } }, }, methods:{ clickCommend(e) { let_this=this; this.$nextTick(() => { this.value-=1; // this.$refs.cmdlist.style.marginLeft = _this.windowWidth+this.value+"px";this.$refs.cmdlist.style.left=_this.windowWidth+this.value+"px"; }); }, ... ... },
.marquee-box{ position: relative; width: 100%; height: 50px; background-color: white; overflow: auto; background-color: #f8f8f8; } #pWidth{ margin-top: 0px!important; margin-bottom: 0px!important; position: absolute; /* 作了修改*/top: 0; /* 作了修改*/left: 100%; /* 作了修改*/line-height: 50px; display: block; word-break: keep-all; text-overflow: ellipsis; white-space: nowrap; overflow:hidden; font-family: 微软雅黑; fontSize:14px; background-color: #f8f8f8}
其实无论是横向滚动还是上下滚动,都是使用计时器和改变元素的位置实现滚动的。然后就能实现了