JS-JQ-滾動條回到頂部

1、思路:html

  獲得document.documentElement.scrollTop的值,賦值爲0chrome

  documentElement :屬性可返回文檔的根節點express

2、知識動畫

  $(window) 獲取的是窗口
  $('body,html')獲取的是文件自己firefox

  $('html,body') 爲何要寫2個,是由於 firefox ie 不支持 body, chrome 支持的是body, 因此爲了兼容就這樣寫htm

 

!!! - CSSip

<style>
  body{height:3000px;}
  #div1{width: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>文檔

 

!!! - HTMLget

<div id="div1"></div>it

 

!!! - 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)   }) })

相關文章
相關標籤/搜索