Javascript/React onClick 滚动设置金额向下/向上



我在弄清楚如何使按钮单击向下滚动时遇到了问题,例如每次点击 30px。

假设我有两个带有此类图标的div

<div className="info-container">
    <div className="scroll-icon-container" onClick={scrollUp(30)}>
        <ScrollUpIcon />
    </div>
    <div className="scroll-icon-container" onClick={scrollDown(30)}>
        <ScrollDownIcon />
    </div>
    <p>"Huge amount of text that will need scrolling"</p>
</div>

然后两个函数,如

scrollUp(number: amountToScroll){
   //Scroll the "info-container" up amountToScroll pixels
}
scrollDown(number: amountToScroll){
   //Scroll the "info-container" down amountToScroll pixels
}

到目前为止,我能找到的只是在jquery中,或者如何使其滚动到特定元素,但我正在寻找一个以像素%或任何有效的方式向下滚动的量。

首先,

您可以定义一个变量或状态来维护滚动位置。

让我们将状态作为 scrollPosition 并将其初始化为 0。

现在在滚动函数中:

scrollUp(amountToScroll){
    this.setState({
        scrollPosition : this.state.scrollPosition + amountToScroll
    })
    window.scrollTo(0, this.state.scrollPosition)
}

现在在向下滚动功能中:

scrollDown(amountToScroll){
    this.setState({
        scrollPosition : this.state.scrollPosition - amountToScroll
    })
    window.scrollTo(0, this.state.scrollPosition)
}

使用window.scrollBy( pixelsToScrollRight, pixelsToScrollDown )方法。

因此,您可以拥有如下内容,而不是scrollUp()scrollDown()方法:

scroll(number: amountToScroll){
  //amount to scroll is negative to scroll up
  window.scrollBy(0 , amountToScroll)
}

如果你想看看在div内滚动:如何滚动到div内的元素?

最新更新