手机版返回顶部代码
纯JS版本的手机版返回顶部插件,很实用。下面分享js代码:
(function gotop(anchor){ window.addEventListener("load",function(){ window.setTimeout(function(){window.scrollTo(0,1);},300); },false) document.body.scrollTop=0; var screenheight=480; var imgH = 45 ;//滑动元素的高度 var gotop = document.querySelector(anchor) function addStyle(p,s){ var ps=p['style'],s; for(var k in s){ps[k] = s[k];} } gotop.addEventListener('click',function(){ addStyle(gotop,{'opacity':'0.8'}) window.setTimeout(function(){window.scrollTo(0,1);},300); },false) document.body.addEventListener('touchstart',function(){ addStyle(gotop,{ '-webkit-transition-duration':'', '-webkit-transition-timing-function':'', 'opacity':'0' }) },false); document.addEventListener('scroll',function(){ if(document.body.scrollTop<100) return; var screenheight = parseInt(windows.innerHeight)-imgH; var scrollLength = document.body.scrollTop +screenheight; addStyle(gotop,{ '-webkit-transition-duration':'400ms', '-webkit-transition-timing-function':'ease-out-in', 'opacity':'0.8', '-webkit-transform':'translate3d(0,'+scrollLength+'px,0)' }) },false) })('#gotop');这里的“#gotop”就是您的返回顶部按钮的ID,这是用自执行函数写的,您也可以封装成插件。
下面的代码是返回顶部按钮的css样式,您可以自己定义:
#gotop{ -webkit-transform:translate3d(0,0,0); position:absolute; right:5px; opacity:0; -webkit-transition-property:-webkit-transform; cursor:pointer; }