vue使用list动态加载数据滚动条自动滚动到底部,用户手动滚动则取消

vue使用list动态加载数据滚动条自动滚动到底部,用户手动滚动则取消,第1张

场景: list中的数据是动态的,每次保证滚动条能自动滚动到最底部,查看最新的一条记录。如果用户手动 *** 作滚动条如拖动或鼠标滚轮滑动,则取消自动滚动。
解决方案 一、使用scrollTop =scrollHeight

1.使用scrollTop 时,容器必须要有height并且overflow为auto或scroll

<div class="container">
.container {
   height: 100%;
   overflow: scroll;
}

2.借助vue生命周期updated

	data(){
	  return{
	    // 用户手动滚动标志
		activeSlide: false, 
	  }
	}
	
    updated() {
      let div = document.getElementsByClassName("container");
      if (div && div.length > 0) {
        // 添加鼠标滚轮滚动监听
        window.addEventListener("mousewheel", this.wheelScroll);
        // 添加区域内点击监听
        div[0].onmousedown = () => {
          this.activeSlide = true;
          div[0].onmousedown = null;
        };
        if (!this.activeSlide) {
          div[0].scrollTop = div[0].scrollHeight;
        }
      }
    },
    methods:{
      getList(){
      // 获取列表list内容之前改为false
      this.activeSlide = false;
      // ...
      },
      wheelScroll(e) {
        e = e || window.event;
        // wheelDelta !== 0 为上下滚动
        if (e.wheelDelta !== 0) {
          this.activeSlide = true;
          // 移除监听
          window.removeEventListener("mousewheel", this.wheelScroll);
        }
      }
    }

总结:这种方式会让滚动条一直在底部,不会有一节一节向下滑动的感觉

二、使用setInterval定时
	data(){
	  return{
	    // 用户手动滚动标志
		activeSlide: false, 
		slideTimerIds:[]
	  }
	}

    methods:{
      getList(){
        // 获取列表list内容之前改为false
        this.activeSlide = false;
        this.slide();
        // 如果获取不到则使用nextTick
        // this.$nextTick(() => {
           // this.slide();
        });
        // ...
      },
      slide() {
        // 添加鼠标滚轮滚动监听
        window.addEventListener("mousewheel", this.wheelScroll);
        let div = document.getElementsByClassName("container");
        // 添加日志区域点击监听
        div[0].onmousedown = () => {
          this.clearSlideInterval();
          div[0].onmousedown = null;
        };
        this.slideTimerIds.push(setInterval(this.slideTimer, 1000, div));
      },
     slideTimer(div) {
        if (div[0].scrollTop + div[0].clientHeight >= div[0].scrollHeight) {
          this.clearSlideInterval(false);
        } else {
          div[0].scrollTop += 1000;
        }
      },
      wheelScroll(e) {
        e = e || window.event;
        if (e.wheelDelta !== 0) {
          this.clearSlideInterval();
          window.removeEventListener("mousewheel", this.wheelScroll);
        }
      },
      // 清除定时器
      clearSlideInterval(active = true) {
        this.slideTimerIds.forEach((id) => {
          clearInterval(id);
        });
        this.slideTimerIds = [];
        // 手动或自动滚动
        this.activeSlide = active;
      }
    }

总结:这种方式会使滚动条1s滚动1000px

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1320716.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-11
下一篇 2022-06-11

发表评论

登录后才能评论

评论列表(0条)

保存