react 示例:
componentDidMount() {
// 第一次渲染完成时进行滚动监听
window.addEventListener('scroll', this.handleScroll, false);
}
componentWillUnmount() {
// 组件移除时去除滚动监听
window.removeEventListener('scroll', () => {})
}
handleScroll = () => {
this.setState(() => {
return {
backTop: window.pageYOffset >= 400
}
})
}
scrollTo = (el, from = 0, to = 0, duration = 500, endCallback) => {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000 / 60);
}
);
}
const difference = Math.abs(from - to);
const step = Math.ceil(difference / duration * 50); // 总的长度 除以 总时间 再乘以 50 => 2000/1000 * 50 = 100 相当于一步走100px
function scroll(start, end, step) {
let d = 0;
if (start = end) { // 如果相等了 就停止执行
endCallback && endCallback();
return;
} else if (start > end) { // 如果开始位置大于最后位置 开始做减法
d = (start - step < end) ? end : start - step;
} ele {
d = (start + step > end) ? end : start + step;
}
if (el === window) {
window.scrollTo(start, d); // 就从开始 start 滚动到 d 处
} else {
el.scrollTop = d;
}
window.requestAnimationFrame(() => scroll(d, end, step));
}
scroll(from, to, step);
};
gotoTop = () => {
setTimeout(() => {
const sTop = document.documentElement.scrollTop || document.body.scrollTop;
this.scrollTo(window, sTop, 0, 1000, () => {
console.log('已经滑到顶部啦');
});
}, 0);
}
vue 的话一般直接在Vue原型上写就可以。