soarli

一个优雅的回顶部特效
<!DOCTYPE html> <html> <head> <t...
扫描右侧二维码阅读全文
06
2020/06

一个优雅的回顶部特效

<!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;

灵感来源:

www.happyla.net

blog.csdn.net/weixin_33782386/article/details/93138214

最后修改:2022 年 01 月 07 日 06 : 17 PM

发表评论