
实现页面返回顶部的效果需要用到很多JavaScript知识,比如:function(),animate,fadeOut等等,如有不清楚的小伙伴可以参考PHP中文网的相关文章,或者访问 JavaScript视频教程。
实例描述:用户往下滑动页面,当滚动条距离顶部的距离大于100px时,用fadeIn显示返回按钮,当点击按钮返回顶部后,按钮消失,具体代码如下:
HTML部分:
<div id="wrapper"> <div class="cont1"></div> <div class="cont2"></div> <div class="cont3"></div> <div class="cont4"></div> <a href="javascript:void(0)" id="toTop" style="display: block;"> </a> </div>
CSS部分:
*{margin: 0;padding: 0;}
#wrapper{margin: 0 auto;width: 500px;}
.cont1{height: 500px;background-color: wheat;}
.cont2{height: 500px;background-color: honeydew;}
.cont3{height: 500px;background-color: blueviolet;}
.cont4{height: 500px;background-color: pink;}
#toTop {display: none;text-decoration: none;position: fixed;bottom: 20px;right: 20px;overflow: hidden;width: 50px;height: 50px;background: url(img/icon_top.png) no-repeat center center;}JavaScript部分:
注:因为用的是jQuery写的,要记得引入jQuery文件啊
$(function(){
//当滚动条的位置处于距顶部100像素以下时,跳转链接出现,否则消失
$(function () {
$(window).scroll(function(){
if ($(window).scrollTop()>100){
$("#toTop").fadeIn(1000);
}
else
{
$("#toTop").fadeOut(1000);
}
});
//当点击跳转链接后,回到页面顶部位置
$("#toTop").click(function(){
$('body,html').animate({scrollTop:0},1000);
return false;
});
});
});效果图:

以上给大家分享了如何用jQuery实现HTML页面返回顶部的代码,步骤很详细,简单易懂,初学者可以自己动手尝试,看看你的代码能不能实现回到顶部的效果,希望这篇文章对你有所帮助!
【相关教程推荐】
1. jQuery中文参考手册
2. jQuery视频教程
3. bootstrap教程
