vue实现吸顶效果

代码实现:
html中,设置id,v-bind:class名,如下:

<ul class="box_fixed" id="boxFixed" :class="{'is_fixed' : isFixed}"></ul>

js:监听鼠标行为

        data() {
            return {
                isFixed: false,
                offsetTop: 0
            }
        },
        mounted() {
            window.addEventListener('scroll', this.initHeight);
            this.$nextTick(() => {
                //获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置 
                this.offsetTop = document.querySelector('#boxFixed').offsetTop;
            })
        },
        methods: {
            initHeight() {
                // 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 (被卷曲的高度)
                var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
                //如果被卷曲的高度大于吸顶元素到顶端位置 的距离
                this.isFixed = scrollTop > this.offsetTop ? true : false;
            },
        },
        //回调中移除监听
        destroyed() {
            window.removeEventListener('scroll', this.handleScroll)
        }

css:设置吸顶元素宽高及实现吸顶时的 position: fixed;

 .box_fixed{
    width: 500px;
    height: 40px;
    border: 2px dashed pink;
    border-radius: 20px;
    margin: 0 auto;
    line-height: 40px;
    background: #eeeeee;
  }
  .is_fixed{
    position: fixed;
    top: 0;
    z-index: 999;
  }

效果图:


变化前

变化后

参考:
1、Vue-实现吸顶效果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。