<!DOCTYPE html>
<html>
<head>
<title>gotop</title>
<script type="text/javascript">
(function () {
function goTop(acceleration, time) {
acceleration = acceleration || 0.1;
time = time || 16;
var dx = 0;
var dy = 0;
var bx = 0;
var by = 0;
var wx = 0;
var wy = 0;
if (document.documentElement) {
dx = document.documentElement.scrollLeft || 0;
dy = document.documentElement.scrollTop || 0;
}
if (document.body) {
bx = document.body.scrollLeft || 0;
by = document.body.scrollTop || 0;
}
var wx = window.scrollX || 0;
var wy = window.scrollY || 0;
var x = Math.max(wx, Math.max(bx, dx));
var y = Math.max(wy, Math.max(by, dy));
var speed = 1 + acceleration;
window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
if (x > 0 || y > 0) {
var invokeFunction = "MGJS.goTop(" + acceleration + ", " + time + ")";
window.setTimeout(invokeFunction, time);
}
}
window["MGJS"] = {};
window["MGJS"]["goTop"] = goTop;
//window["MGJS"]["goDown"] = goDown;
})();</script>
</head>
<body>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1><h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1><h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1><h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1><h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1><h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<h1>test</h1>
<a id="gotop" href="#" onclick="MGJS.goTop();return false;">回到顶部</a>
</body>
</html>
21.07.05更新
按照需要自动隐藏回顶部按钮:
window.onscroll = function () {
if (document.documentElement.scrollTop + document.body.scrollTop > 100) {
document.getElementById("scrollto").style.display = "block";
}
else {
document.getElementById("scrollto").style.display = "none";
}
}
需要默认回顶部元素display:none;
。
灵感来源:
blog.csdn.net/weixin_33782386/article/details/93138214
版权属于:soarli
本文链接:https://blog.soarli.top/archives/442.html
转载时须注明出处及本声明。