该代码可以实现滚动浏览器、任意dom元素水平方向
、垂直方向
的滚动条至指定位置。
常见场景有:置顶
、置底
滚动效果:水平方向滚动
垂直方向滚动
代码:
/**
* 设置浏览器或元素滚动条滚动距离
* @param ele dom元素或window对象
* @param direction 滚动条方向,默认为y,可选值有:x、y
* @param to 滚动条即将滚动到到位置
* @param duration 时长(可选)
* @param onDone 完成后的回调(可选)
* @param onScroll 正在滚动中的回调(可选)
* @returns {boolean}
*/
function scrollTo (ele, direction, to, duration, onDone, onScroll) {
if (!ele) {
return false;
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000/60);
}
);
}
if (!direction) {
direction = 'y';
}
direction = direction == 'x' ? 'x' : 'y';
var doDone = function () {
if (typeof onDone == 'function') {
onDone();
}
}
var callOnScroll = function () {
if (typeof onScroll == 'function') {
onScroll();
}
}
var attr = direction == 'x' ? 'scrollLeft' : 'scrollTop';
var scrollLeft = function (ele) {
if (ele && ele.nodeType == 1) {
return ele.scrollLeft;
}
return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
}
var scrollTop = function (ele) {
if (ele && ele.nodeType == 1) {
return ele.scrollTop;
}
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
}
if (!duration || duration <= 0) {
if (ele === window) {
window.scrollTo(direction === 'x' ? to : scrollLeft(), direction === 'y' ? to : scrollTop());
} else {
ele[attr] = to;
}
callOnScroll();
doDone();
return true;
}
var diff = to - ele[attr];
if (ele === window) {
diff = to - (direction == 'x' ? scrollLeft() : scrollTop());
}
var perTick = (diff / duration) * 10;
window.requestAnimationFrame(function () { // 实现缓动效果
if (ele === window) {
let x = scrollLeft();
let y = scrollTop();
window.scrollTo(direction === 'x' ? (x + perTick) : x, direction === 'y' ? (y + perTick) : y);
callOnScroll();
if (direction == 'x' ? scrollLeft() : scrollTop() !== to) {
scrollTo(ele, direction, to, duration - 10, onDone, onScroll);
} else {
callOnScroll();
doDone();
}
return;
}
ele[attr] += perTick;
if (ele[attr] !== to) {
callOnScroll();
tool.scrollTo(ele, direction, to, duration - 10, onDone, onScroll);
} else {
callOnScroll();
doDone();
}
});
return true;
}
调用:
var ele = document.getElementById('xxx');
// 滚动至元素最右侧
scrollTo(ele, 'x', ele.scrollWidth, 200);
// 滚动至元素顶部
scrollTo(ele, 'y', 0, 200);
// 滚动至浏览器顶部
scrollTo(window, 'y', 0, 200);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。