javascript - 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 中或如何使其滚动到特定元素,但我正在寻找一个以像素% 为单位向下滚动的设定量或任何有效的方法。
解决方案
首先,您可以定义一个变量或状态来保持滚动位置。
让我们将 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)
}
推荐阅读
- typescript - 如何在打字稿中使用 sinon 存根表达中间件?
- html - 使用 Active Directory 组为单页 HTML 站点启用 Windows 身份验证
- node.js - 使用 APNS 发送带有图像的 Firebase 推送通知
- excel - 对于输入日期,查找具有相同月份和年份的日期单元格
- janusgraph - 有没有办法在 JanusGraph 中使用 UUID 而不是 id 块分配?
- c# - C# 驱动程序聚合查找具有另一个集合的嵌入式数组
- sharepoint-2013 - SharePoint 2013,从 HTML 中提取文本并在 SP 中填充联系人项目
- c++ - 使用setprecision时如何阻止数字四舍五入?
- reactjs - 使用 react-leaflet 将层绑定到功能组件中的 onEachFeature
- php - PHP 从具有查询字符串的 URL 获取 JSON