style代码
<style>
#height{
height: 1400px;
}
#db{
text-align: right;
}
#dibu{
text-align: right;
}
</style>
html代码
<div id="dibu">回到底部</div>
<div id="height">你好</div>
<div id="db">回到顶部</div>
js代码
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>//jQuery的引入
<script>
window.onscroll=function(){
//方法1 获取滚动条的高度
var h=document.documentElement.scrollTop||document.body.scrollTop;
//方法2 用jQuery的方法 获取滚动条的高度
console.log($(document).scrollTop());
//回到顶部 jquery 方法
var db=document.getElementById('db');//获取点击按钮
db.onclick=function(){
$('body,html').animate({scrollTop:0},500)
}
//原生的方法的缓冲效果比jQuery的缓冲效果要好
var time=null;
db.onclick=function(){
time=setInterval(function(){
var h=document.documentElement.scrollTop||document.body.scrollTop;
var speed=Math.floor(h/5);
document.documentElement.scrollTop=document.body.scrollTop=h-speed;
if(h==0){
clearInterval(time)
}
},50)
}
//回到底部的方法
var dibu=document.getElementById('dibu');//按钮的获取
//获取整个页面的高度
var bodyHeight=$('body').height();
console.log(bodyHeight)
dibu.onclick=function(){
$('body,html').animate({scrollTop:bodyHeight},500)
}
}
</script>