一、思路:
得到document.documentElement.scrollTop的值,赋值为0
documentElement :属性可返回文档的根节点
二、知识
$(window) 获取的是窗口
$('body,html')获取的是文件本身
$('html,body') 为什么要写2个,是因为 firefox ie 不支持 body, chrome 支持的是body, 所以为了兼容就这样写
!!! - CSS
<style>
body{height:3000px;}
#div1{50px;height:50px;box-sizing: border-box;background:rosybrown;position:fixed;
_position:absolute;_top:expression(documentElement.scrollTop+"px");
z-index:9999;bottom:30px;right:30px;}
</style>
!!! - HTML
<div id="div1"></div>
!!! - JavaScript
基础版本:小白就看这个吧,这个是基础版本
window.onload=function()
{
var div1=document.getElementById('div1');
div1.onclick=function()
{
//FF:document.documentElement.scrollTop获取滚动条滚动的高度
//IE:document.body.scrollTop获取滚动条滚动的高度
document.documentElement.scrollTop=document.body.scrollTop=0;
}
}
中等版本:这个有了动画效果
window.onload=function()
{
var div1=document.getElementById('div1');
var byse=true;
var timer=null;
window.onscroll=function()
{
if(!byse) //如果回到顶部的时候byse=false,
{
clearInterval(timer);
}
byse=false;
}
div1.onclick=function()
{
timer=setInterval(function(){
var s=document.documentElement.scrollTop||document.body.scrollTop;
var iSpeed=Math.floor(-s/8);
var timer=null;
if(s==0)
{
clearInterval(timer);
}
byse=true;
document.documentElement.scrollTop=document.body.scrollTop=s+iSpeed;
},30);
}
}
!!!- JQuery
$(function(){
$('#div1').bind('click',function(){
var s=0;
$('body,html').animate({
scrollTop:s,
},30)
})
})