<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>点击回到顶部</title> <link rel="stylesheet" type="text/css" href="static/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="icon" type="image/x-icon" href="static/images/icon.ico" /> <link rel="stylesheet" type="text/css" href="static/style4.css"> <script type="text/javascript" src="static/jquery-3.3.1.js"></script> <script type="text/javascript"> $(function(){ $(window).scroll( function(){ if($(window).scrollTop()>150){ $('.backTop').fadeIn(1000) }else{ $('.backTop').fadeOut(1000) } }) }) </script> </head> <body> <a href="" id="backTop"></a> <div class="bcground"> <a href="#backTop"><div class="backTop"><span class="fa fa-arrow-circle-up"></span><br>返回顶部</div></a> </div> </body> </html>
*{margin: 0px;padding: 0px;} .bcground{width: 1200px;height: 2000px; margin: 0px auto;background: #ccc;} .backTop{width: 50px;height: 30px; background: #B7B4B4;position: fixed;bottom: 100px;right: 20px;font-size: 10px;text-align: center;border-radius: 2px;display: none;} a{color: #fff;text-decoration: none;} .fa-arrow-circle-up{margin-top: 3px;}
利用if判断,以scrollTop()计算滚动条到浏览器窗口到顶部的距离为条件,实现fadeIn()/fadeOut()效果