1.要求:实现轮询公告,鼠标放上停止轮询,鼠标移开继续轮询
2.实现效果如下:
3.思考:文本从最右侧开始滚动,因此开始start为容器宽度500,滚动到最左侧时为-(滚动文本宽度),超出宽度从新滚动
4.代码如下:
<template>
<div>
<div class="box" @mouseenter="stopDone" @mouseleave="startLL">
<div class="new" ref="new" :style="{left:start+'px'}">
<div class="new_item"><a href="#">7:10 商务部:前五个月使用外资同比增长15%</a></div>
<div class="new_item"><a href="#">7:15 中国成功实现基中反拦截导弹</a></div>
<div class="new_item"><a href="#">7:20 珠江疫情分控,居民拖箱子逃离</a></div>
<div class="new_item"><a href="#">7:30 东南地区及沿海有特大暴雨</a></div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
maxWidth:0,
start:'500',
interval:{},
flag:0,//1:开启,0介绍
}
},
mounted(){
let newObj = this.$refs.new;
console.log('new',newObj.clientWidth);
this.maxWidth = '-'+newObj.clientWidth;
//this.startDone();
//setInterval(()=>{this.startDone();},100);//setInterval刷新不流畅会有断续问题,改用requestAnimationFrame
this.flag = 1;
this.interval = this.startDone;
window.requestAnimationFrame(this.interval);
},
methods:{
startLL(){
console.log('start');
this.flag = 1;
window.requestAnimationFrame(this.interval);
},
startDone(){
this.start = Number(this.start)-1;
if(Number(this.start)<Number(this.maxWidth)){//到底重新循环
this.start = '500'
}
if(this.flag){//关闭跳出轮询
window.requestAnimationFrame(this.interval);
}
// this.interval = window.requestAnimationFrame(()=>{
// this.start = Number(this.start)-4;
// if(Number(this.start)<Number(this.maxWidth)){//到底重新循环
// this.start = '500'
// }
// });
},
stopDone(){
console.log('stop');
this.flag = 0;
//window.cancelAnimationFrame(this.interval);
},
},
}
</script>
<style scoped>
.box{
width: 500px;
overflow-x: hidden;
border: 1px solid #333;
position: relative;
line-height: 24px;
height: 24px;
}
.new{
display: flex;
flex-wrap: nowrap;
position: absolute;
top: 0;
}
.new_item{
font-size: 13px;
margin-right: 40px;
white-space: nowrap;
}
</style>