实现效果:
页面有返回顶部、底部按钮,返回顶部按钮当页面滚动超过一屏时显示,返回底部按钮当页面到达底部时隐藏;
返回时带有滚动返回效果,可控制返回速度。
<!doctype html>
<html>
<head>
<title>返回顶部/底部</title>
<meta http-equiv='charset' content='utf-8'/>
<script type='text/javascript' src='jquery-1.7.2.js'></script>
<script type='text/javascript'>
//显隐按钮
function showReposBtn(){
var clientHeight = $(window).height();
var scrollTop = $(document).scrollTop();
var maxScroll = $(document).height() - clientHeight;
//滚动距离超过可视一屏的距离时显示返回顶部按钮
if( scrollTop > clientHeight ){
$('#retopbtn').show();
}else{
$('#retopbtn').hide();
}
//滚动距离到达最底部时隐藏返回底部按钮
if( scrollTop >= maxScroll ){
$('#rebtmbtn').hide();
}else{
$('#rebtmbtn').show();
}
}
window.onload = function(){
//获取文档对象
$body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $("html") : $("body")) : $("html,body");
//显示按钮
showReposBtn();
}
window.onscroll = function(){
//滚动时调整按钮显隐
showReposBtn();
}
//返回顶部
function returnTop(){
$body.animate({scrollTop: 0},400);
}
//返回底部
function returnBottom(){
$body.animate({scrollTop: $(document).height()},400);
}
</script>
<style type='text/css'>
#retopbtn{
position:fixed;
bottom:10px;
right:10px;
}
#rebtmbtn{
position:fixed;
top:10px;
right:10px;
}
</style>
</head>
<body>
<button id='rebtmbtn' οnclick='returnBottom()'>底部</button>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<h1>a</h1>
<button id='retopbtn' οnclick='returnTop()'>顶部</button>
</body>
</html>