WebページにgotoTop(上部に戻る)ボタンを追加

9597 ワード


  
  
  
  
  1. /** 
  2.  *  gotop 。 
  3.  *  JS , CSS HTML 。 
  4.  * 
  5.  * @param int width  ,  
  6.  * - 0   
  7.  * - -1   
  8.  * -     
  9.  * @return void 
  10.  * @link http://blog.830725.com/post/add-goto-top-button.html 
  11.  */ 
  12. function gotoTop(width) 
  13.   document.write('<a id="goto-top">^</a>'); 
  14.   var gotop = document.querySelector('#goto-top'); 
  15.   /*  CSS  */ 
  16.   gotop.style.visibility='hidden'
  17.   gotop.style.cursor='pointer'
  18.   gotop.style.position = 'fixed'
  19.   gotop.style.fontSize='2.5em'
  20.   gotop.style.fontWeight='900'
  21.   gotop.style.textAlign='center'
  22.   gotop.style.background = 'gray'
  23.   gotop.style.borderRadius = '0.2em'
  24.   gotop.style.width='1.4em'
  25.   gotop.style.height='1em'
  26.   gotop.style.top = (document.documentElement.clientHeight / 2) + 100 + 'px'
  27.   gotop.style.opacity='0.3'
  28.   gotop.style.visibility = (document.body.scrollTop + document.documentElement.scrollTop > 10) ? 'visible' : 'hidden'
  29.   if(0 == width) 
  30.   { gotop.style.left = '0em';  } 
  31.   else if(-1 == width) 
  32.   { gotop.style.right = '0em';  } 
  33.   else 
  34.   { 
  35.   var resize = function() 
  36.   { 
  37.   var left = (document.documentElement.clientWidth - width) / 2 + width + 10; 
  38.   if((left - gotop.clientWidth) < width) 
  39.   { 
  40.   gotop.style.right='0em'
  41.   gotop.style.left = null;  //  right , left 。 
  42.   } 
  43.   else 
  44.   { 
  45.   gotop.style.left = left + 'px'
  46.   gotop.style.right = null
  47.   } 
  48.   }; 
  49.   resize(); 
  50.   window.addEventListener('resize'function() 
  51.   { 
  52.   resize(); 
  53.   }, false); 
  54.   
  55.   } 
  56.   gotop.addEventListener('mouseover'function() 
  57.   { 
  58.   this.style.opacity='0.8'
  59.   this.style.textDecoration='none'
  60.   }, false); 
  61.   gotop.addEventListener('mouseout'function() 
  62.   { 
  63.   this.style.opacity='0.3'
  64.   }, false); 
  65.   gotop.addEventListener('click'function() 
  66.   { 
  67.   // IE9 opera body.scrollTop 0,chrome documentElement.scrollTop 0 
  68.   //  0 
  69.   var h = document.body.scrollTop + document.documentElement.scrollTop; //   
  70.   var t = window.setInterval(function() 
  71.   { 
  72.   window.scrollTo(0,h -= 100); //  100  
  73.   if(h <= 0) 
  74.   { window.clearInterval(t);  } 
  75.   }, 5); 
  76.   }, false); 
  77.   /*  window.onscroll  */ 
  78.   window.addEventListener('scroll'function() 
  79.   { 
  80.   var scrollTop = document.body.scrollTop + document.documentElement.scrollTop; 
  81.   gotop.style.visibility = scrollTop > 10 ? 'visible':'hidden'
  82.   }, false); 
  83. }; 

原文住所:http://blog.830725.com/post/add-goto-top-button.html
本文は“コードコレクション”のブログから出て、転載して作者と連絡してください!