最近用原生js做项目练手,自己尝试做了下,可以直接复制代码看效果

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>滑入滑出</title>
 6     <style>
 7         #dv1 {
 8             height: 0px;
 9             overflow: hidden;
10         }
11 
12         #dv2 {
13             width: 200px;
14             height: 200px;
15             background: #ace;
16         }
17     </style>
18 </head>
19 <body>
20 <input type="button" id="btn2" value="点击滑出"/>
21 <input type="button" id="btn1" value="点击滑入"/>
22 <div id="dv1">
23     <div id="dv2"></div>
24 </div>
25 <script>
26     var dv = document.getElementById("dv1");
27     document.getElementById("btn1").onclick = function () {
28         animate(dv, "height", 0)
29     }
30     document.getElementById("btn2").onclick = function () {
31         animate(dv, "height", 200)
32     }
33 
34     //兼容代码:获取当前元素样式的值
35     function getStyle(element, attr) {
36         return getComputedStyle ? getComputedStyle(element, null)[attr] : element.currentStyle[attr];
37     }
38 
39     function animate(element, attr, target) {
40         clearInterval(element.timeId);
41         //不清理的话,每一次调用animate这个函数,就会产生一个定时器
42         element.timeId = setInterval(function () {
43             var current = parseInt(getStyle(element, attr));//返回值是元素样式的值,转换成整数进行下面的计算
44             var step = (target - current) / 10;
45             step = step > 0 ? Math.ceil(step) : Math.floor(step);
46             current += step;
47             element.style[attr] = current + "px";
48             if (current == target) {
49                 clearInterval(element.timeId);
50             }
51         }, 20)
52     }
53 </script>
54 </body>
55 </html>
View Code

相关文章: