vue+element ui实现锚点定位

本文实例为大家分享了vue + element ui 实现锚点定位的具体代码,供大家参考,具体内容如下

vue


   
    
    
     
      
      {{item.subjectName}}
     
    
   
   
   
    
{{item.name}}

js

// 滚动触发按钮高亮
methods: {
  onScroll(e) {
            let scrollItems = document.querySelectorAll(".scroll-item");
            console.log(scrollItems)
            console.log(e)
   for (let i = scrollItems.length - 1; i >= 0; i--) {
    // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
    let judge =
     e.target.scrollTop >=
     scrollItems[i].offsetTop - scrollItems[0].offsetTop;
    if (judge) {
                    console.log(i)
     this.activeStep = i.toString();
     break;
    }
   }
  },
  jump(index) {
            console.log(index)
   let target = document.querySelector(".scroll_cls");
   let scrollItems = document.querySelectorAll(".scroll-item");
   // 判断滚动条是否滚动到底部
   if (target.scrollHeight <= target.scrollTop + target.clientHeight) {
                console.log(index)
                console.log(typeof index)
    this.activeStep = index;
   }
            let total = scrollItems[index].offsetTop - scrollItems[0].offsetTop; // 锚点元素距离其offsetParent(这里是body)顶部的距离(待滚动的距离)
            console.log(total)
            let distance = document.querySelector(".scroll_cls").scrollTop; // 滚动条距离滚动区域顶部的距离
            console.log(distance)
   // let distance = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset // 滚动条距离滚动区域顶部的距离(滚动区域为窗口)
   // 滚动动画实现, 使用setTimeout的递归实现平滑滚动,将距离细分为50小段,10ms滚动一次
   // 计算每一小段的距离
   let step = total / 50;
   if (total > distance) {
    smoothDown(document.querySelector(".scroll_cls"));
   } else {
    let newTotal = distance - total;
    step = newTotal / 50;
    smoothUp(document.querySelector(".scroll_cls"));
   }

   // 参数element为滚动区域
   function smoothDown(element) {
    if (distance < total) {
     distance += step;
                    element.scrollTop = distance;
     setTimeout(smoothDown.bind(this, element), 10);
    } else {
     element.scrollTop = total;
    }
   }

   // 参数element为滚动区域
   function smoothUp(element) {
    if (distance > total) {
     distance -= step;
     element.scrollTop = distance;
     setTimeout(smoothUp.bind(this, element), 10);
    } else {
     element.scrollTop = total;
    }
   }

   document.querySelectorAll('.scroll-item').forEach((item, index1) => {
     if (index === index1) {
       item.scrollIntoView({
         block: 'start',
         behavior: 'smooth'
       })
     }
   })
  },
  },
 mounted() {
       this.$nextTick(() => {
           console.log(1)
           window.addEventListener('scroll', this.onScroll,true)
       })
    },

css

.scroll_cls {
    height: 500px;
 overflow: auto;
}

转载自:原文链接点击这里

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(vue+element ui实现锚点定位)