有时候页面过长,滚动条来过来拉过去太费劲,介于jQuery的强大功能,一键点击返回顶部这个功能很容易就实现了。
下面开始介绍实现步骤。
1、页面引入jQuery脚步,版本无要求。
2、准备一张漂亮的图片。我这里使用的是这个。
3、在需要用的页面插入以下html标签,放在html标签内就行了。
4、返回顶部按钮的样式。
.back-top { bottom: 35px; overflow: hidden; position: fixed; right: 10px; width: 50px; display:none; } .back-top a { background: url("/images/back-top.png") no-repeat scroll 0 0 transparent; display: block; height: 50px; outline: 0 none; text-indent: -9999em; width: 50px; } .back-top a:hover { background-position: -50px 0; }
5、返回顶部按钮jQuery代码。
$(function(){ ///绑定点击事件 $("div.back-top a").click(function() { $('html, body').animate({ scrollTop: 0 }, 500); }); ///绑定窗口滚动事件 $(window).scroll(function() { //滚动条距离顶端的距离大于窗口高度的时候,也就是滚动了一屏的时候 if ($(window).scrollTop() > $(window).height()) { if ($("div.back-top").not(":visible")) $("div.back-top").fadeIn(100); } else { if ($("div.back-top").is(":visible")) $("div.back-top").fadeOut(100); } }); });