原生js实现 返回顶部
目录结构:
test
│ test.html
├─css
│ goToTop.css
├─images
│ toTop.png
└─scripts
goToTop.js
style.css
- /* goToTop div's css
the html is :<div class="toTop"><span class="toTopWords">返回顶部</span></div>*/.toTop{width:42px;height:42px;font-size:19px;line-height:19px;padding:4px;text-align: center;position: fixed;bottom:10px;right:10px;/*display: none;*/background: #404040 url(../images/toTop.png) no-repeat -37px center;}.toTop:hover{color: #fff;font-family:'Microsoft Yahei';cursor: pointer;background: #404040 url(../images/toTop.png) no-repeat -2000px center;}.toTopWords{display: none;}
goToTop.js
//返回顶部小插件,放在右下角var toTop=document.getElementsByClassName('toTop')[0];toTop.onmouseover=function(){var toTopWords = this.getElementsByClassName('toTopWords')[0];toTopWords.style.display="block";return false;};toTop.onmouseout=function(){var toTopWords = this.getElementsByClassName('toTopWords')[0];toTopWords.style.display="none";return false;};toTop.onclick=function(e){goToTop(50,10);};/*** goToTop: function to scroll to Top* author: JHP* Date: 2015-09-06*///step: pixels of one step//stepTime: time to scrollBy(0,-step) in millisecondsfunction goToTop(step,stepTime){var yoff = window.pageYOffset;var cnt = Math.ceil(yoff/step);var timer1=setInterval(function(){if(window.pageYOffset>0){window.scrollBy(0,-step);}}, stepTime);setTimeout(function(){clearInterval(timer1);}, (stepTime+1)*cnt);}
test.html
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>New Document</title><link type="text/css" rel="stylesheet" href="./css/goToTop.css" /></head><body>...省略中间部分<div class="toTop"><span class="toTopWords">返回顶部</span></div><script type="text/javascript" src="./scripts/goToTop.js"></script></body></html>
附件列表

浙公网安备 33010602011771号