最近得到一个需求,新闻滚动,滚动到底部以后切换下一条消息继续滚动,
具体如下:如果当前内容出现滚动条,则触发持续滚动,到底部后停留3秒,切换下一条新闻,如果内容刚好没有滚动条,则停留3秒切换下一条
首先滚动代码
html部分:
<div v-if="newsList.length > 0" class="news-con" ref="news">
<div v-for="(item,index) in newsList" :key="'aa'+index" v-show="index==mark">
<div class="news-title">{{item.title}}</div>
<div class="news-author">{{item.author}}</div>
<div class="news-digest" v-html="item.digest"></div>
<div class="news-source">{{item.source}} {{item.createTime}}</div>
</div>
</div>
然后方法部分:
//新闻切换autoplayNews(){ 声明一个mark字段,用来匹配当前index显示当前页面
let that = this;
if(that.mark<that.newsList.length-1){
that.mark++;
}else{
that.mark = 0;
}
},
//滚动条持续滚动
rollNews(){
var that = this;
function Marquee() {
var scrollNum = that.news.scrollHeight- that.news.clientHeight;//获取可滚动得距离
if (that.news.scrollTop == scrollNum) { //判断到底部或者刚好满屏没有滚动条
that.news.scrollTop = 0;
clearInterval(that.sortNews); //如果到底部则清除滚动条的定时器
setTimeout(that.rollNews,3000);//停留三秒后重启滚动条的定时器(重要,被这一步卡了好久)
that.autoplayNews(); //切换下一个页面
} else {
that.news.scrollTop++;
}
}
this.sortNews = setInterval(Marquee, 30); //设置定时器
}
把方法放在mounted中
mounted() { //在mounted中获取news的dom
this.news = this.$refs.news; this.rollNews();
}