前言
结合具体场景实战requestAnimationFrame
业务场景:
h5 技术: vue2 vant2
评论可以自动的向上滚动 并且可以手动拖拉滚动条 查看上面的评论
你可以把requestAnimationFrame认为是浏览器内部提供的一个钩子函数,执行时间是在 每一帧渲染开始前执行 是不会阻塞js 主线程执行 ,也不会触发多余的重绘操作
下面是简单的demo
代码
代码比较简单就直接贴出来
//commentView.vue
<template>
<section class="contain" ref="myScroll">
<div class="contain-item" v-for="item in list" :key="item.id">
<div class="headImg" />
<div class="comment">{{ getContent(item) }}</div>
</div>
</section>
</template>
<script>
import { comment } from "@/comment/data.js";
export default {
data() {
return {
list: comment,
scrollTemp: null,
dom:null
};
},
methods: {
getContent(val) {
let obj = JSON.parse(val.content);
return obj.contentText || "暂无";
},
start() {
if(this.getScrollBottom()>0){
this.dom.scrollTop = this.dom.scrollTop+1
}
window.requestAnimationFrame(this.start)
},
getScrollBottom(){
//获取滚动条到底部的距离
let scrollTop = this.dom.scrollTop
let scrollHeight = this.dom.scrollHeight
let clientHeight = this.dom.clientHeight
let scrollBottom = scrollHeight - scrollTop - clientHeight
return scrollBottom
}
},
computed: {},
mounted() {
this.dom = this.$refs.myScroll;
this.start()
},
};
</script>
<style scope lang="scss">
p {
margin: 0;
padding: 0;
}
.contain {
width: 100%;
height: 300px;
overflow-y: auto;
font-size: 14px;
background: #efefef;
.contain-item {
width: 100%;
overflow: hidden;
.headImg {
margin-top: 10px;
float: left;
left: 0;
width: 25px;
height: 25px;
border-radius: 50%;
background-image: url("@/assets/logo.png");
background-size: cover;
margin-left: 30px;
}
.comment {
float: right;
text-align: left;
padding: 4px;
margin: 10px 30px 10px 0;
border-radius: 4px;
right:12px;
background: #fff;
line-height: 25px;
width: 70%;
word-break: break-all;
text-overflow: ellipsis;
display: -webkit-box; /** 对象作为伸缩盒子模型显示 **/
-webkit-box-orient: vertical; /** 设置或检索伸缩盒对象的子元素的排列方式 **/
-webkit-line-clamp: 2; /** 显示的行数 **/
overflow: hidden; /** 隐藏超出的内容 **/
}
}
}
</style>
### 模拟数据 可以直接添
说明
1. 在元素渲染到页面后 通过ref 拿到容器的dom
2. 通过getScrollBottom 计算 滚动条距离容器底部的距离
3. 开启 start方法 是一个递归执行 每一帧控制滚动条向下移动一定距离(前提是滚动条没有触到底部) 可以自己控制速度
了解更多requestAnimationFrame:
mdn requestAnimationFrame