Skip to content

Commit 52fe12f

Browse files
committed
go top
1 parent ed8e841 commit 52fe12f

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

gotop_fromYangJi.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function goTop(acc, t) {
2+
const acceleration = acc || 0.1;
3+
const time = t || 16;
4+
5+
const document = window.document;
6+
7+
let x1, y1, x2, y2 = 0;
8+
if (document.documentElement) {
9+
x1 = document.documentElement.scrollLeft || 0;
10+
y1 = document.documentElement.scrollTop || 0;
11+
}
12+
if (document.body) {
13+
x2 = document.documentElement.scrollLeft || 0;
14+
y1 = document.documentElement.scrollTop || 0;
15+
}
16+
const x3 = window.scrollX || 0;
17+
const y3 = window.scrollY || 0;
18+
//滚动条到页面顶部的水平距离
19+
const x = Math.max(x1, Math.max(x2, x3));
20+
//滚动条到页面顶部的垂直距离
21+
const y = Math.max(y1, Math.max(y2, y3));
22+
const speed = 1 + acceleration;
23+
//滚动距离= 目前距离/速度 滚动距离会越来越小(速度>1)
24+
window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
25+
//如果距离不为零 继续调用迭代本函数
26+
if (x > 0 || y > 0) {
27+
window.setTimeout(goTop, time);
28+
}
29+
return;
30+
}

0 commit comments

Comments
 (0)