我有我在我的项目之一,用于平滑滚动顶部的脚本,我做了一个小重构滚动高度你的div(滚动底部)我希望它有帮助。
scroll.js
function currentYPosition() {
if (self.pageYOffset) return self.pageYOffset;
if (document.documentElement && document.documentElement.scrollHeight) return document.documentElement.scrollHeight;
if (document.body.scrollHeight) return document.body.scrollHeight;
return 0;
}
function elmYPosition(eID) {
let elm = document.getElementById(eID);
let y = elm.offsetHeight;
let node = elm;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetHeight;
}
return y;
}
export default function smoothScroll(eID, string) {
let startY = currentYPosition();
let stopY = elmYPosition(eID);
let distance = stopY > startY ? stopY - startY : startY - stopY;
let speed = Math.round(distance/10);
let speedTimeout = 250;
if (speed >= 100) speed = 100;
if (string) speed = 1;
let step = Math.round(distance/25);
let leapY = stopY > startY ? startY + step : startY - step;
let timer = 0;
if (stopY > startY) {
for (let i = startY; i < stopY; i += step) {
setTimeout('window.scrollTo(0, ' + leapY + ')', timer * speed);
leapY += step;
if (leapY > stopY) leapY = stopY;
timer++;
}
return;
}
for (let i = startY; i > stopY; i -= step) {
setTimeout('window.scrollTo(0, ' + (leapY) + ')', timer * speed);
leapY -= step;
if (leapY < stopY){
leapY = stopY;
}
timer++;
}
}
你应该导入这个您的组件里面,有2个参数(你的元素的ID,在这种情况下,你可以使用参考。第二个是我已经用于治疗的滚动速度的字符串。
import scroll from './your-path/scroll.js';
.
.
.
<ul className='options-holder'>
{
this.state.items.map((item, index) => (
<li key={item.id} className={`option ${index === 0 ? 'first' : ''}`} ref={el => (this.formLi = el)}>
<div className='circle' onClick={this.removeItem} />
<p className='item-text'>{ item.text }</p>
</li>
))
}
<li key={0} className={`option form ${this.state.items.length === 0 ? 'only' : ''}`} ref={el => (this.formLi = el)}>
<div className='circle form' />
<form className='new-item-form' onSubmit={this.handleSubmit}>
<input
autoFocus
className='new-item-input'
placeholder='Type something and press return...'
onChange={this.handleChange}
value={this.state.text}
ref={(input) => (this.formInput = input)} />
</form>
</li>
Idk你如何在你的渲染中映射这个LI,但你应该进行验证,如果有属性溢出,你应该运行滚动。
有一个合理的答案,你的组件跳到第一个元素,你击中了第一个元素的ref,而不是最后一个。
可能的解决方法:
scroll(this.state.items[this.state.items.length - 1]);
更新1:吉斯特原scroll.js的,scrolling to the top
在这种情况下,也许你将最后一个li移出ul并添加另一个包装 –
为什么我要这样做,而不是只滚动ul? –