js返回顶部事件

xiaoxiao2021-02-28  53

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> div{cursor:default;width:20px;height:80px;line-height:20px;border:1px solid black;position:fixed;right:0;bottom:20px;text-align:center;display:none;} </style> </head> <body style="height:5000px"> <div> 返回顶部 </div> </body> <script> function css(obj, attr, val) { if (arguments.length == 3) { // 修改 if (obj.currentStyle && attr == 'opacity') { // 如果返回的不是undefined(转换为false)就是IE浏览器 obj.style.filter = 'alpha(opacity:' + val + ')'; } else if (attr == 'opacity') { obj.style[attr] = val / 100; } else { //obj.style[attr] = val + 'px'; obj.style[attr] = val; } } else if (arguments.length == 2) { // 获取 if (obj.currentStyle) { if (attr == 'opacity') { return parseInt(obj.currentStyle.filter.split(':')); } else { return parseInt(obj.currentStyle[attr]); } } else { if (attr == 'opacity') { return parseInt(Math.round(getComputedStyle(obj, null)[attr] * 100)); } else { var value = parseInt(getComputedStyle(obj, null)[attr]); return value; } } } } for (var i=0;i<300;i++){ document.write('Line ' + (i + 1) + '<br/>'); } var oDiv = document.getElementsByTagName('div')[0]; document.body.onscroll = function(){ var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > 600){ css(oDiv, 'display', 'block'); }else{ css(oDiv, 'display', 'none'); } }; oDiv.onclick = function(){ // 没有动画效果 // document.documentElement.scrollTop = 0; // document.body.scrollTop = 0; clearInterval(oDiv.timeHandler); oDiv.timeHandler = setInterval(function(){ var cur = scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (cur != 0){ var speed = (0 - cur) / 10; speed = speed>0?Math.ceil(speed):Math.floor(speed); document.documentElement.scrollTop = cur + speed; document.body.scrollTop = cur + speed; }else{ console.log(11); clearInterval(oDiv.timeHandler); } }, 30); }; </script> </html>
转载请注明原文地址: https://www.6miu.com/read-84370.html

最新回复(0)