首页 电脑 电脑学堂 查看内容

javascript回到顶部特效

2016-8-2 12:45 1413 0

摘要: 本文实例为大家分享了javascript回到顶部效果,供大家参考,具体内容如下 ?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 ...

本文实例为大家分享了javascript回到顶部效果,供大家参考,具体内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
 <title>回到顶部效果(原生js)</title>
 <style type="text/css">
  body{
   margin: 0;
 
  }
  .bg{
   width: 1022px;
   margin: 0 auto;
  }
  .btn{
   display: none;
   width: 75px;
   height: 75px;
   background:url(../images/网页top小图标(返回顶部)/返回顶部-085.png) no-repeat left top;
   position: fixed;
   left: 50%;
   margin-left: 530px;
   bottom: 10px;
   text-indent: -9999px;
   outline: none;
  }
  .btn:hover{
   background-position: 0 -75px;
  }
 </style>
  
 <script
 var timer=null;
 var isScroll=true;
 //1.2构造oScroll函数
 function oScroll(){
  var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容
  var oSpeed=Math.ceil(osTop/4);//滚动速度
  document.documentElement.scrollTop=document.body.scrollTop=osTop-oSpeed;
  if(osTop==0){//判断到达顶部,清理定时器
   clearInterval(timer);
  }
  isScroll=true;
 }
       
 window.onload=function() {
  var obtn=document.getElementById('btn');//获取按钮元素
  var clientHeight=document.documentElement.clientHeight||document.body.clientHeight;
 
  // 1.点击返回按钮事件
  btn.onclick=function(){//为按钮绑定点击事件
   timer=setInterval(oScroll,50);
  }
  window.onscroll=function() {
   var osTop=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>
 <div class="bg">
  <img src="../images/jz.webp">
 </div>
 <a href="javascript:void(0);" title="返回顶部" id="btn" class="btn">返回顶部</a>
</body>
</html>

以上就是本文的全部内容,希望对大家学习JavaScript程序设计有所帮助。

声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花

鸡蛋

最新评论

返回顶部