Realize the ceiling function in Vue

Requirement: When the scroll bar is pulled down, the title bar will be displayed at the top.
Two methods:
1. Monitor the distance from the box to the top of the browser. If the distance is 0, position it.
2. Use the attribute position of c3: 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)
    },

in 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
        },

Determine whether to locate by class name

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

The second method is simple and easy

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

insert image description here

Guess you like

Origin blog.csdn.net/weixin_48164217/article/details/118386394