美文网首页
页面快捷导航 + 滚动监听 + 返回顶部 三件套

页面快捷导航 + 滚动监听 + 返回顶部 三件套

作者: sunxiaochuan | 来源:发表于2020-11-03 15:46 被阅读0次

前言

该代码只作为作者的存储,以及读者的借鉴使用。

源码


    /**
     * 顶部固定定位快捷导航
     * index 当前点击的索引值
     */
    quickNavHandle(index, { value }) {
      index > 4 && index--
      this.pageNavIndex = index
      const selectorAll = Array.prototype.slice.call(
        document.querySelectorAll('.tab-bar')
      )
      document.body.scrollTop = selectorAll[index].offsetTop
      document.documentElement.scrollTop = selectorAll[index].offsetTop
    },
    /**
     * 点击返回顶部动画
     */
    backtopHandle() {
      document.body.scrollTop = 0
      document.documentElement.scrollTop = 0
      this.pageNavIndex = 0
    },
    /**
     * 监听页面滚动行为
     */
    watchScrollHandle() {
      this.$nextTick(() => {
        let time = null
        window.addEventListener('scroll', (e) => {
          const selectorAll = Array.prototype.slice.call(
            document.querySelectorAll('.tab-bar')
          )
          if (time) clearTimeout(time)
          time = setTimeout(() => {
            const scrollTop =
              document.documentElement.scrollTop || document.body.scrollTop
            selectorAll.forEach((element, index) => {
              scrollTop >= element.offsetTop - 1 && (this.pageNavIndex = index)
            })
          }, 100)
        })
      })
    }

相关文章

网友评论

      本文标题:页面快捷导航 + 滚动监听 + 返回顶部 三件套

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