原生js实现 返回顶部

目录结构:
test
│  test.html
├─css
│      goToTop.css
├─images
│      toTop.png
└─scripts
        goToTop.js

style.css
  1. /* goToTop div's css
  2. the html is :
  3. <div class="toTop"><span class="toTopWords">返回顶部</span></div>
  4. */
  5. .toTop{
  6. width:42px;
  7. height:42px;
  8. font-size:19px;
  9. line-height:19px;
  10. padding:4px;
  11. text-align: center;
  12. position: fixed;
  13. bottom:10px;
  14. right:10px;
  15. /*display: none;*/
  16. background: #404040 url(../images/toTop.png) no-repeat -37px center;
  17. }
  18. .toTop:hover{
  19. color: #fff;
  20. font-family:'Microsoft Yahei';
  21. cursor: pointer;
  22. background: #404040 url(../images/toTop.png) no-repeat -2000px center;
  23. }
  24. .toTopWords{
  25. display: none;
  26. }
goToTop.js
  1. //返回顶部小插件,放在右下角
  2. var toTop=document.getElementsByClassName('toTop')[0];
  3. toTop.onmouseover=function(){
  4. var toTopWords = this.getElementsByClassName('toTopWords')[0];
  5. toTopWords.style.display="block";
  6. return false;
  7. };
  8. toTop.onmouseout=function(){
  9. var toTopWords = this.getElementsByClassName('toTopWords')[0];
  10. toTopWords.style.display="none";
  11. return false;
  12. };
  13. toTop.onclick=function(e){
  14. goToTop(50,10);
  15. };
  16. /**
  17. * goToTop: function to scroll to Top
  18. * author: JHP
  19. * Date: 2015-09-06
  20. */
  21. //step: pixels of one step
  22. //stepTime: time to scrollBy(0,-step) in milliseconds
  23. function goToTop(step,stepTime){
  24. var yoff = window.pageYOffset;
  25. var cnt = Math.ceil(yoff/step);
  26. var timer1=setInterval(function(){
  27. if(window.pageYOffset>0){
  28. window.scrollBy(0,-step);
  29. }
  30. }, stepTime);
  31. setTimeout(function(){clearInterval(timer1);}, (stepTime+1)*cnt);
  32. }
test.html
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>New Document</title>
  6. <link type="text/css" rel="stylesheet" href="./css/goToTop.css" />
  7. </head>
  8. <body>
  9. ...省略中间部分
  10. <div class="toTop"><span class="toTopWords">返回顶部</span></div>
  11. <script type="text/javascript" src="./scripts/goToTop.js"></script>
  12. </body>
  13. </html>





附件列表

     

    posted @ 2015-09-06 16:00  homer3000  阅读(201)  评论(0)    收藏  举报