记vue下悬浮贴合顶部实现

个人github地址vue

 Aim:实现移动端滑到某一个位置实现贴合导航条效果。git

效果图以下:github

 

方案:bash

1.监听滚动条移动距离,当达到触发距离,将tab栏fixed。dom

2.定时器实时监听tab栏距离顶部距离。ide

3.只适配移动端下的touchmove事件,触发判断tab距离顶部距离。函数


实现:布局

   尝试了监听scroll 监听 某个函数 以下,无效果,怀疑是层级dom定位。性能

且监听成功距离一直为0.ui

提供代码记录:

mounted(){
    this.$refs.content.addEventListener('scroll',this.handleScroll,true)
},
methods:{
    handleScroll(e){
        console.log(e)
    }
}复制代码


方案二:

 这是最后才考虑的一种,经过定时器监听,性能太差。由于方案三实现,没作尝试。


方案三:

created(){
  this.$nextTick(()=>{
    // document.querySelectorAll('.vue-slider-piecewise-dot').style.borderRadius = 0;
    [25,50,75].forEach((v,k)=>{
       document.querySelectorAll('.vue-slider-piecewise-item')[v].style.zIndex=3;
       document.querySelectorAll('.vue-slider-piecewise-dot')[v].style.background = 'rgb(229, 235, 245)'
       document.querySelectorAll('.vue-slider-piecewise-dot')[v].style.width = '15px'
       document.querySelectorAll('.vue-slider-piecewise-dot')[v].style.height = '15px'
       document.querySelectorAll('.vue-slider-piecewise-dot')[v].style.borderRadius = '15px'
    })
 // 实现贴合监听
    this.box = this.$refs.content;  // box是贴合的导航条
    document.querySelector('#gemtrans').addEventListener('touchmove',() => { // 监听整个单页
      console.log(this.box.getBoundingClientRect().top)
      let top = this.box.getBoundingClientRect().top; // 获取顶部距离
      if(top<=48){
        document.querySelector('.v-tabs__bar').style.position = 'fixed'
        document.querySelector('.v-tabs__bar').style.top= '49px'
        document.querySelector('.v-tabs__bar').style.width= '100%'
        document.querySelector('.v-tabs__bar').style.zIndex= 3
      }else {
        document.querySelector('.v-tabs__bar').style.position = 'relative'
        document.querySelector('.v-tabs__bar').style.top= 'initial'
        document.querySelector('.v-tabs__bar').style.width= 'initial'
        document.querySelector('.v-tabs__bar').style.zIndex= 'initial'
      }
    })
    
  })

},复制代码


网上大可能是方案一,或者采用插件,但由于项目布局的缘由不是很通用,采用方案三,简单实现效果也不错了~