一、原理
- 监听当前页面滚动事件
- 当滚动到一定像素显示回到顶部的按钮
- 给回到顶部按钮绑定点击事件,点击按钮让滚动条回到顶部并隐藏按钮
二、实现代码
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>回到顶部demo</title>
<style type="text/css"> .up{ position:fixed; bottom:20px; right:20px; width:10px; display:none; } </style>
</head>
<body>
<div style="background:rgb(200,200,200);height:2000px;">我很长</div>
<a id="up" href="javascript:;" class="up">回到顶部</a>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
//绑定页面滚动事件
$(window).bind('scroll',function(){
var len=$(this).scrollTop();
if(len>=100){
//显示回到顶部按钮
$('#up').show();
}else{
//影藏回到顶部按钮
$('#up').hide();
}
})
//绑定回到顶部按钮的点击事件
$('#up').click(function(){
//动画效果,平滑滚动回到顶部
$(document).animate({ scrollTop: 0 });
//不需要动画则直接
//$(document).scrollTop(0) })
</script>
</html>