javascript回到顶部特效
本文实例为大家分享了javascript回到顶部效果,供大家参考,具体内容如下
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=Edge,chrome=1"> <title>回到顶部效果(原生js)</title> <styletype="text/css"> body{ margin:0; } .bg{ width:1022px; margin:0auto; } .btn{ display:none; width:75px; height:75px; background:url(../images/网页top小图标(返回顶部)/返回顶部-085.png)no-repeatlefttop; position:fixed; left:50%; margin-left:530px; bottom:10px; text-indent:-9999px; outline:none; } .btn:hover{ background-position:0-75px; } </style> <script> vartimer=null; varisScroll=true; //1.2构造oScroll函数 functionoScroll(){ varosTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容 varoSpeed=Math.ceil(osTop/4);//滚动速度 document.documentElement.scrollTop=document.body.scrollTop=osTop-oSpeed; if(osTop==0){//判断到达顶部,清理定时器 clearInterval(timer); } isScroll=true; } window.onload=function(){ varobtn=document.getElementById('btn');//获取按钮元素 varclientHeight=document.documentElement.clientHeight||document.body.clientHeight; //1.点击返回按钮事件 btn.onclick=function(){//为按钮绑定点击事件 timer=setInterval(oScroll,50); } window.onscroll=function(){ varosTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容 if(osTop>clientHeight){ btn.style.display="block"; }else{ btn.style.display="none"; } if(!isScroll){ clearInterval(timer); } isScroll=false; } } </script> </head> <body> <divclass="bg"> <imgsrc="../images/jz.jpg"> </div> <ahref="javascript:void(0);"title="返回顶部"id="btn"class="btn">返回顶部</a> </body> </html>
以上就是本文的全部内容,希望对大家学习JavaScript程序设计有所帮助。