用vue寫一個滾動到某個位置dom加上className的自定義指令!

  • 108
  • 0

用directive來封裝一個滾動到某個地方,讓選單可以高量的功能!

知識點

  1. getBoundingClientRect


#js
export default {
  install (Vue) {
    Vue.directive('scroll-active', {
      inserted (el, binding) {
        const { target, className } = binding.value
        const targetDom = document.querySelector(`${target}`)
        function debounce (cb, delay) {
          let timer = null
          return function () {
            clearTimeout(timer)
            timer = setTimeout(cb, delay)
          }
        }
        function getScrollTop () { // 瀏覽器最上方位置
          return Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
        }
        function getCurrentBottomPos () { // 瀏覽器最下方位置
          return getScrollTop() + document.documentElement.clientHeight
        }

        window.addEventListener('scroll', debounce(() => {
          const currentBottomPos = getCurrentBottomPos()
          if (currentBottomPos > targetDom.getBoundingClientRect().top + document.documentElement.scrollTop && currentBottomPos < targetDom.getBoundingClientRect().bottom + document.documentElement.scrollTop) {
            if (el.classList.contains(className)) return
            el.classList.add(className)
          } else {
            el.classList.remove(className)
          }
        }), 100)
      }
    })
  }
}
#註冊
import ScrollActive from '@/plugins/scrollActive'
Vue.use(ScrollActive)
#使用
v-scroll-active="{
   target:'.fpShare',//目標容器
   className:'active'//要加上的class
}"

參考

https://shubo.io/get-bounding-client-rect/