requestAnimationFrame实现全屏滚动评论

本文通过一个Vue2+Vant2的H5评论滚动实例,详细讲解了如何利用requestAnimationFrame实现评论列表的自动平滑滚动效果。通过在每一帧渲染前更新滚动条位置,确保不会阻塞主线程并避免多余重绘。同时,介绍了获取滚动条底部距离的方法,以及如何启动和控制滚动动画。这是一个实用的前端开发技巧,适用于创建动态滚动效果。
摘要由CSDN通过智能技术生成

前言

结合具体场景实战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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值