<!DOCTYPE html>
<html lang="en">
<head>
<title>返回顶部/底部
</title>
<meta charset="UTF-8">
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></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' onclick='returnBottom()'>底部
</button>
<div style="width: 600px; height: 500px; background: #ddd;"></div>
<div style="width: 600px; height: 500px; background: #F8B88E;"></div>
<div style="width: 600px; height: 500px; background: #BF6969;"></div>
<button id='retopbtn' onclick='returnTop()'>顶部
</button>
</body>
</html>
效果图:
另外一种写法:
$(
function(){
//返回顶部
$('#back_top').on('click'
,move);
$(window).on('scroll',
function(){
checkPostion($(window).height());
});
function move() {
$('html,body'
).animate({
scrollTop:0
},800
);
}
function checkPostion(pos) {
if($(window).scrollTop() >
pos) {
$('#back_top'
).fadeIn();
} else {
$('#back_top'
).fadeOut();
}
}
});
转载于:https://www.cnblogs.com/huanghuali/p/7045689.html
转载请注明原文地址: https://mac.8miu.com/read-407441.html