html [返回顶部]下拉300px后,会出现按钮,点击返回顶部#JavaScript

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html [返回顶部]下拉300px后,会出现按钮,点击返回顶部#JavaScript相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>返回页面顶部</title>
  <style>
    body {
      height: 4000px;
    }
    
    #top {
      top: 0px;
      height: 50px;
      width: 100%;
      background-color: #111;
      color: #fff;
    }
    
    #up {
      position: fixed;
      width: 80px;
      height: 22px;
      bottom: 30px;
      right: 30px;
      border: 1px solid #aaa;
      border-radius: 3px;
      display: none;
    }
    
    #up:hover {
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div id="top">
    劳资是顶部
  </div>
  <div id="up" title="回到顶部">
    UP to TOP
  </div>
</body>
<script>
  window.onscroll = function() {
    //获取对象
    var up = document.getElementById("up");
    var timer = null;
    var isTop = true;
    //客户端高度
    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    //在滚动的时候增加判断
    //获取滚动条距离顶部的高度
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    //300px的判断,是否出现按钮
    if (osTop - clientHeight >= 300) {
      up.style.display = 'block';
    } else {
      up.style.display = 'none';
    }
    //判断,到顶了就不再动了
    if (!isTop) {
      clearInterval(timer);
    }
    isTop = false;
    //绑定事件
    up.onclick = function() {
      window.scrollTo(0, 0);
    }
  }
</script>

</html>

以上是关于html [返回顶部]下拉300px后,会出现按钮,点击返回顶部#JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

html中按钮不能用相对定位吗?

如何用JS实现返回顶部?

html css 返回顶部按钮位置怎么固定?

js : 怎么设置网页滚动条超过800px后,显示“返回顶部”的按钮?

网页返回顶部按钮js实现

点击回到顶部的按钮