JS-JQ-滾動條回到頂部


一、思路:

  得到document.documentElement.scrollTop的值,賦值為0

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

二、知識

  $(window) 獲取的是窗口
  $('body,html')獲取的是文件本身

  $('html,body') 為什么要寫2個,是因為 firefox ie 不支持 body, chrome 支持的是body, 所以為了兼容就這樣寫

 

!!! - CSS

<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>

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM