Vue 中实现 div 在页面滚动后停留在页面固定位置

实现效果如下:

在这里插入图片描述

需要设置的vue组件

<script>
export default {
   // 页面创建钩子函数中添加事件监听
   created() {
     this.listenerFunction()
   },
   methods: {
    // 事件监听 监听页面的 scroll 事件,回调方法为 handleScroll
    listenerFunction(e) {
      document.addEventListener('scroll', this.handleScroll, true)
    },
    // 编写滚动条事件
    handleScroll() {
      // 获取滚动条元素对象
      let ele = document.getElementsByClassName('page-router-wrapper')[0]
      // 获取需要固定的元素对象
      let editorNav = document.getElementsByName('n_my_editor_nav')[0]
      // 判断滚动条的高度(大于240,给固定元素添加 class)
      if (ele.scrollTop > 240) {
        editorNav.classList.add('suspension')
      } else {
        editorNav.classList.remove('suspension')
      }
    }
   	}
    // 销毁事件监听
    beforeDestroy() {
      document.removeEventListener('scroll', this.listenerFunction)
    }
  }
  </script>

css

 <style>
	.suspension{
	    top: 66px;
	    z-index: 99999;
	    position: fixed;
	    border-top: 1px solid #eee;
	    width: calc(100% - 248px);
	}
</style>
发布了14 篇原创文章 · 获赞 4 · 访问量 3867

猜你喜欢

转载自blog.csdn.net/qq_37237495/article/details/102625363