用JS实现回到顶部效果,到制度位置显示显示或者隐藏,回到顶部动画效果,实现封装,可当插件;
1 <script> 2 window.onload = function(){ 3 function createTemp(){ 4 var temp = document.createElement("div"); 5 temp.style.width = 70 + 'px'; 6 temp.style.height = 25 + 'px'; 7 temp.style.border = 1 + 'px solid slategray'; 8 temp.innerHTML = "回到顶部"; 9 temp.style.display = "none"; 10 temp.style.position = "fixed"; 11 temp.style.bottom = "20%"; 12 temp.style.right = "0px"; 13 temp.setAttribute('id','to_top'); 14 document.body.appendChild(temp); 15 } 16 createTemp(); 17 18 var to_top = (function(){ 19 var wrapper = document.getElementById("to_top"); 20 window.addEventListener("scroll", function(){ 21 var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop || 0; 22 wrapper.style.display = (scrollTop > 300) ? 'block' : 'none' 23 }) 24 wrapper.addEventListener("click",function(){ 25 var isTop = document.documentElement.scrollTop || document.body.scrollTop; 26 var time = setInterval(function(){ 27 var osTop = document.documentElement.scrollTop || document.body.scrollTop; 28 document.documentElement.scrollTop -= isTop/20; 29 document.body.scrollTop -= isTop/20; 30 if(osTop <= 0){ 31 clearInterval(time); 32 } 33 },10) 34 }) 35 return function(){ 36 } 37 38 }()) 39 to_top(); 40 41 } 42 </script>