我如何滚动某个元素(而不是整个页面)一定数量的像素,例如每次单击按钮时像素为100px(没有链接,因为每次都需要固定数量的像素),所以我使用ReactJS 16。
答案 0 :(得分:0)
您可以在要滚动的元素上使用scrollBy
。一个普通的JS示例:
let btn = document.getElementById('btn');
let box = document.getElementById('box');
btn.addEventListener('click', function() {
box.scrollBy({top:100, behavior: "smooth"});
});
#box {
width: 300px;
height: 100px;
overflow-y: scroll;
}
#inner-box {
width: 100px;
height: 1000px;
}
.content {
height: 50px;
display: block
}
<button id="btn">scroll</button>
<div id="box">
<div id="inner-box">
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
</div>
</div>
这是ReactJS版本:
class Scrollable extends React.Component {
constructor(props) {
super(props);
this.scroll = this.scroll.bind(this);
this.box = React.createRef();
}
scroll() {
this.box.current.scrollBy({top:100, behavior: "smooth"});
}
render() {
return (
<div>
<button onClick={this.scroll}>scroll</button>
<div id="box" ref={this.box}>
<div id="inner-box">
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
<div class="content">
content
</div>
</div>
</div>
</div>
);
}
}
演示在Codepen