美文网首页
组件吸顶功能实现

组件吸顶功能实现

作者: 阿猪_341c | 来源:发表于2020-06-21 11:41 被阅读0次

吸顶功能实现记录
主要用的是scrolltop的距离来控制是否将组件定位改为fix,只需要用原生js即可实现。
我们在vue中使用。
首先在mounted钩子函数中添加监听事件

mounted(){
        window.addEventListener('scroll',this.initHeight)
    },

我们不直接写函数而是使用this.initHeight是为了方便操作initHeight函数
然后定义方法

methods:{
        initHeight(){
            let scrollTop = window.pageYOffset || document.scrollTop || document.body.scrollTop;
            this.isFixed = scrollTop > 152? true:false;
        }
    },

这里需要注意浏览器的兼容,不同浏览器对于获取scrolltop的方式可能都是不一样的
除此之外,我们还需要定义事件销毁函数,为了提高浏览器性能

destroyed(){
        window.removeEventListener('scroll',this.initHeight)
    }

组件吸顶功能就完成啦,完整代码一览

<div class="nav-bar" :class="{'is_fixed':isFixed}">你好啊,我叫赛利亚</div>
data(){
      return {
        isFixed:false
      }
    },
    mounted(){
        window.addEventListener('scroll',this.initHeight)
    },
    methods:{
        initHeight(){
            let scrollTop = window.pageYOffset || document.scrollTop || document.body.scrollTop;
            this.isFixed = scrollTop > 152? true:false;
        }
    },
    destroyed(){
        window.removeEventListener('scroll',this.initHeight)
    }
  }
&.is_fixed{
      position:fixed;
      top:0;
      width:100%;
      box-shadow: 0 5px 5px red;
    }

相关文章

网友评论

      本文标题:组件吸顶功能实现

      本文链接:https://www.haomeiwen.com/subject/rpioxktx.html