首页 > 解决方案 > Javascript/React onClick 向下/向上滚动设置量

问题描述

我在弄清楚如何使按钮 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 中或如何使其滚动到特定元素,但我正在寻找一个以像素% 为单位向下滚动的设定量或任何有效的方法。

标签: javascriptreactjs

解决方案


首先,您可以定义一个变量或状态来保持滚动位置。

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

现在在 scrollUp 函数中:

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

现在在 scrollDown 函数中:

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

推荐阅读