WebページにgotoTop(上部に戻る)ボタンを追加
- /**
- * gotop 。
- * JS , CSS HTML 。
- *
- * @param int width ,
- * - 0
- * - -1
- * -
- * @return void
- * @link http://blog.830725.com/post/add-goto-top-button.html
- */
- function gotoTop(width)
- {
- document.write('<a id="goto-top">^</a>');
- var gotop = document.querySelector('#goto-top');
- /* CSS */
- gotop.style.visibility='hidden';
- gotop.style.cursor='pointer';
- gotop.style.position = 'fixed';
- gotop.style.fontSize='2.5em';
- gotop.style.fontWeight='900';
- gotop.style.textAlign='center';
- gotop.style.background = 'gray';
- gotop.style.borderRadius = '0.2em';
- gotop.style.width='1.4em';
- gotop.style.height='1em';
- gotop.style.top = (document.documentElement.clientHeight / 2) + 100 + 'px';
- gotop.style.opacity='0.3';
- gotop.style.visibility = (document.body.scrollTop + document.documentElement.scrollTop > 10) ? 'visible' : 'hidden';
- if(0 == width)
- { gotop.style.left = '0em'; }
- else if(-1 == width)
- { gotop.style.right = '0em'; }
- else
- {
- var resize = function()
- {
- var left = (document.documentElement.clientWidth - width) / 2 + width + 10;
- if((left - gotop.clientWidth) < width)
- {
- gotop.style.right='0em';
- gotop.style.left = null; // right , left 。
- }
- else
- {
- gotop.style.left = left + 'px';
- gotop.style.right = null;
- }
- };
- resize();
- window.addEventListener('resize', function()
- {
- resize();
- }, false);
-
- }
- gotop.addEventListener('mouseover', function()
- {
- this.style.opacity='0.8';
- this.style.textDecoration='none';
- }, false);
- gotop.addEventListener('mouseout', function()
- {
- this.style.opacity='0.3';
- }, false);
- gotop.addEventListener('click', function()
- {
- // IE9 opera body.scrollTop 0,chrome documentElement.scrollTop 0
- // 0
- var h = document.body.scrollTop + document.documentElement.scrollTop; //
- var t = window.setInterval(function()
- {
- window.scrollTo(0,h -= 100); // 100
- if(h <= 0)
- { window.clearInterval(t); }
- }, 5);
- }, false);
- /* window.onscroll */
- window.addEventListener('scroll', function()
- {
- var scrollTop = document.body.scrollTop + document.documentElement.scrollTop;
- gotop.style.visibility = scrollTop > 10 ? 'visible':'hidden';
- }, false);
- };
原文住所:http://blog.830725.com/post/add-goto-top-button.html
本文は“コードコレクション”のブログから出て、転載して作者と連絡してください!