1.介绍及思路分析:
在很多公司的网站中,鼠标滚动一定高度(以150px为例)之后,会出现“返回顶部”的标签。
“返回顶部”标签被固定到窗口的指定位置,位置始终不变。
当滚动的距离高度小于指定高度后,该“返回顶部”的标签消失。
另外,“返回顶部标签”绑定点击事件,通过鼠标点击,实现文档回到顶部的效果。
2.完整代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>返回顶部</title> <style type="text/css"> * { padding: 0; margin: 0; } .header { width: 100%; height: 100px; background: gray; text-align: center; font-size: 20px; line-height: 100px; position: fixed; left: 0; right: 0; top: 0; } .content { width: 100%; height: 1500px; background: blueviolet; text-align: center; font-size: 20px; padding-top: 100px; } .footer { width: 100%; height: 100px; background: grey; text-align: center; font-size: 20px; line-height: 100px; } .toTop { width: 70px; height: 70px; border-radius: 50%; background: greenyellow; text-align: center; line-height: 70px; /*返回顶部标签固定定位*/ position: fixed; right: 35px; bottom: 35px; z-index: 999; font-size: 14px; } .toTop:hover { background: green; font-size: 16px; cursor: pointer; color: red; } </style> </head> <body> <div class="wrapper"> <div class="header">顶部导航栏部分</div> <div class="content"> <p>div.wrapper>(div.header+div.content+div.footer+div.toTop)快速生成代码</p> <p>content部分的高度大于屏幕的高度,仅仅是为了出现滚动条而已。</p> </div> <div class="footer">底部</div> <div class="toTop">回顶部</div> </div> </body> </html> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { // 初始时,“返回顶部”标签隐藏 $(".toTop").hide(); $(window).scroll(function() { // 若滚动的高度,超出指定的高度后,“返回顶部”的标签出现。 if($(document).scrollTop() >= 150) { $(".toTop").show(); } else { $(".toTop").hide(); } }) // 绑定点击事件,实现返回顶部的效果 $(".toTop").click(function() { $(document).scrollTop(0); }) }) </script>
3.效果展示
一下分别为:滚动前、滚动后、点击“返回顶部”后的效果对比