我想创建一个变量以防止用户重复单击,但是它不起作用

时间:2019-07-09 11:15:19

标签: javascript vue.js

我编写了一些代码来使滚动动画,当用户单击按钮时,滚动条会平滑滚动到某处。

我不希望用户重复单击该按钮以使代码再次运行,所以我创建了一个变量来防止它运行,但是可悲的是,代码似乎发生冲突。

如何使它正常工作?

它适用于vue项。它是一个全局函数,我为此创建了一个js文件并导入我的vue组件。

这是我的代码:

// scrollToisClick is the variable to prevent repeat click
let scrollToisClick = true
export function scrollToAnywhere(location) {
  if (scrollToisClick) {
    let docEl = document.documentElement, top_distance = docEl.scrollTop, scroll_height = docEl.scrollHeight, per_distance = 0, scrollToAnimation, between_distance = Math.abs(location - top_distance)
    // I set it be false
    scrollToisClick = false
    // Get the scrollbar scroll to top or bottom. P.s.It's not necessary
    if (location > top_distance) {
      scrollToAnimation = setInterval(() => {
        per_distance += between_distance / 50
        window.scrollTo(0, top_distance + per_distance)
      }, 20)
      // monitor if user scroll by himself,stop scroll animate
      window.addEventListener('scroll', () => {
        if (docEl.scrollTop > top_distance + per_distance - 10) {
          clearInterval(scrollToAnimation)
          scrollToAnimation = null
          // I don't know how to remove monitor so I guess it makes the variable be true when the animate already complete
          scrollToisClick = true
          per_distance = null
          top_distance = null
        } else {
          setTimeout(() => {
            clearInterval(scrollToAnimation)
            scrollToAnimation = null
            scrollToisClick = true
            per_distance = null
            top_distance = null
          }, 1000)
        }
      })
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我找到原因了,这是因为我设置了一个EventListener并且没有删除它,这是我修改后的代码:

function clear() {
  isClick = true
  clearInterval(scrollToAnimation)
  scrollToAnimation = null
  per_distance = null
  top_distance = null
  per_time = 0
}

function monitorWheel() {
  window.removeEventListener('scroll', monitorScroll)
  if (docEl.scrollTop == location) {
    clear()
    window.removeEventListener('wheel', monitorWheel)
    window.removeEventListener('scroll', monitorScroll)
  } else {
    setTimeout(() => {
      clear()
      window.removeEventListener('wheel', monitorWheel)
      window.removeEventListener('scroll', monitorScroll)
    }, per_time * 20)
  }
}

function monitorScroll() {
  if (docEl.scrollTop == location) {
    clear()
    window.removeEventListener('wheel', monitorWheel)
    window.removeEventListener('scroll', monitorScroll)
  } else {
    setTimeout(() => {
      clear()
      window.removeEventListener('wheel', monitorWheel)
      window.removeEventListener('scroll', monitorScroll)
    }, per_time * 20)
  }
}
window.addEventListener('wheel', monitorWheel)
window.addEventListener('scroll', monitorScroll)

此修改后,当滚动动画结束时,EventListener将被删除,然后问题就解决了!