在Vue中实现吸顶的功能

需求:下拉滚动条时标题栏会在顶部显示
两种方法:
1,监听盒子到游览器顶部的距离, 如果距离为0 就定位
2 利用c3的属性 position: sticky;

下面上代码
    mounted() {
        // handleScroll为页面滚动的监听回调
        window.addEventListener('scroll', this.handleScroll)
        this.$nextTick(function() {
            // 这里fixedHeaderRoot是吸顶元素的ID
            let header = document.getElementById('header')
            // 这里要得到top的距离和元素自身的高度
            this.offsetTop = header.offsetTop
            this.offsetHeight = header.offsetHeight
        })
    },
 destroyed() {
		 //在destroyed钩子中移除监听
        window.removeEventListener('scroll', this.handleScroll)
    },

在methods中

     handleScroll() {
            // 得到页面滚动的距离
            let scrollTop =
                window.pageYOffset ||
                document.documentElement.scrollTop ||
                document.body.scrollTop
            // console.log('距离上方控件的位置', this.offsetTop)
            // console.log('控件自身的高度', this.offsetHeight)
            // console.log('页面卷入的高度', scrollTop)
            // 判断页面滚动的距离是否大于吸顶元素的位置
            this.headerFixed = scrollTop > this.offsetTop - this.offsetHeight
        },

通过class名称来判断是否定位

     <div  id="header" :class="headerFixed ? 'isFixed' : ''">
     </div>

第二种方法 简单省事

 position: sticky;
  top: 0;
  left: 0;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48164217/article/details/118386394