【问题标题】:How to set ScrollToTop Button to be active on viewport height?如何将 ScrollToTop 按钮设置为在视口高度上处于活动状态?
【发布时间】:2022-07-12 17:40:48
【问题描述】:

目前我正在使用硬编码的高度点来触发可见的 ScrollToTop 按钮。 我希望在通过视口高度时触发解决方案。

  const { scrollDirection } = useScrollDirection()
  const { scrollPosition } = useScrollPosition()
  const [isVisible, setIsVisible] = useState(false)
  const toggleVisible = () => {
    if (scrollPosition === 0) {
      setIsVisible(false)
    }
    **if (scrollPosition > 800) {
      setIsVisible(true)
    } else if (scrollPosition <= 799) {
      setIsVisible(false)
    }**
  }
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    })
  }
  window.addEventListener("scroll", toggleVisible)

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

    你可以使用window.innerHeight

    const toggleVisible = () => {
        const viewportHeight = window.innerHeight;
        if (scrollPosition === 0) {
            setIsVisible(false)
        }
        **if (scrollPosition > viewportHeight) {
            setIsVisible(true)
        } else if (scrollPosition <= viewportHeight) {
            setIsVisible(false)
        }**
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2022-10-13
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多