js实现顶部悬浮

<!DOCTYPE html> <html lang=en> <head>     <meta charset=UTF-8>     <meta http-equiv=X-UA-Compatible content=IE=edge>     <meta name=viewport content=width=device-width, initial-scale=1.0>     <title>Document</title>     <style>         .top{             width: 100%;             height: 100px;             background-color: aqua;             position: fixed;             top: 0;             left: 0;             display: none;         }         .top input{             width: 500px;             height: 20px;             border: 1px solid #000;             margin: 40px 500px;         }         .box{             width: 20px;         }     </style> </head> <body>     <div class=top>         <input type=text>     </div>     <div class=box>         不要问我 一生曾经爱过多少人          你不懂我伤有多深                  要剥开伤口总是很残忍                  劝你别做痴心人                  多情暂且保留几分                  不喜欢孤独                  却又害怕两个人相处                  这分明是一种痛苦                  在人多时候最沉默                  笑容也寂寞                  在万丈红尘中 啊                  找个人爱我                  当我避开你的柔情后                  泪开始坠落                  是不敢不想不应该                  再谢谢你的爱                  我不得不存在                  像一颗尘埃                  还是会带给你伤害                  是不敢不想不应该                  再谢谢你的爱                  我不得不存在                  在你的未来                  最怕这样就是带给你永远的伤害                  不喜欢孤独                  却又害怕两个人相处                  这分明是一种痛苦                  在人多时候最沉默                  笑容也寂寞                  在万丈红尘中                  找个人爱我                  当我避开你的柔情后                  泪开始坠落                  是不敢不想不应该                  再谢谢你的爱                  我不得不存在                  像一颗尘埃                  还是会带给你伤害                  是不敢不想不应该                  再谢谢你的爱                  我不得不存在 啊                  在你的未来                  最怕这样就是带给你永远的伤害     </div>  </body> <script> //获取top var topbox = document.querySelector('.top') window.onscroll = function(){     var h = document.documentElement.scrollTop || document.body.scrollTop     if(h >= 2000){         topbox.style.display = 'block'     }else{         topbox.style.display = 'none'     }     console.log(h); } </script> </html>

效果图:当滚动条达到一定距离则出现顶部悬浮效果

 

滚动条没动时

 

 滚动条到达了设置距离时