一个很简单的返回顶部按钮的制作,当页面超过指定距离时出现,回到顶部后消失
HTML代码
这里用什么都可以,button,a标签都行,因为我要同时放图片和文字就用了a标签
<div id="backtotop">
<a><img src="__PUBLIC__/Home/images/backtotop.png"><p>back to top</p></a>
</div>
css代码
我这里还有定义img标签和p标签的样式就放了,根据个人需求写
#backtotop{
float: right;
text-align: center;
display: none;
clear: both;
position: fixed;
bottom: 5%;
right: 5%;
cursor: pointer;
}
jq代码
<!--$(windows).scroll是监听页面滚动事件-->
<!--如果需要监听其他的滚动事件,把windows换成你要监听的DOM就行-->
$(window).scroll(function () { <!--当页面滚动条的垂直偏移超过100时显示,否则隐藏-->
if ($(window).scrollTop() > 100) {
$("#backtotop").fadeIn(); //fadeIN,fadeOut时渐入渐出,需要别的动画可以自己改
} else {
$("#backtotop").fadeOut();
}
});
$("div#backtotop").click(function () { <!--点击按钮时回到顶部,速度位500-->
$("body,html").animate({
scrollTop: 0
}, 500);
});