多物体多变化

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>多物体多变化</title>
 6         <style>
 7             div{
 8                  150px;
 9                 height: 150px;
10                 background: red;
11                 margin: 10px;
12                 float: left;
13                 filter:Alpha(opacity:30);
14                 opacity: 0.3;
15                 border: 10px solid blue;
16             }
17         </style>
18     </head>
19     <body>
20         <!--多物体运动中几乎所有属性都不能公用    border、padding等等都能影响offsetheight、offsetwidth等-->
21         <div id="div1"></div>
22         <div id="div2"></div>
23         <input type="text" id="txt1" />
24         <script>
25             var oDiv = document.getElementById('div1');
26             var aDiv = document.getElementById('div2');
27             oDiv.onmouseover = function(){
28                 startMove(this,'height',300);
29             }
30             oDiv.onmouseout = function(){
31                 startMove(this,'height',150);
32             }
33             aDiv.onmouseover = function(){
34                 startMove(this,'opacity',100);
35             }
36             aDiv.onmouseout = function(){
37                 startMove(this,'opacity',30);
38             }
39             function getStyle(obj,name){
40                 if(obj.currentStyle){
41                     return obj.currentStyle[name];
42                 }else{
43                     return getComputedStyle(obj,false)[name];
44                 }
45             }
46             function startMove(obj,attr,iTarget){
47                 clearInterval(obj.timer);
48                 obj.timer = setInterval(function(){
49                     var cur = 0;
50                     if(attr == 'opacity'){
51                         cur = Math.round(parseFloat(getStyle(obj,attr)) * 100);
52                     }else{
53                         cur = parseInt(getStyle(obj,attr));
54                     }
55                     var speed = (iTarget - cur)/6;
56                     speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
57                     if(cur == iTarget){
58                         clearInterval(obj.timer);
59                     }else{
60                         if(attr == 'opacity'){
61                             obj.style.filter = 'Alpha(opacity:' + (cur+speed) + ')';    
62                             obj.style.opacity = (cur + speed)/100;
63                             
64                             document.getElementById('txt1').value = obj.style.opacity;
65                         }else{
66                             obj.style[attr] = cur + speed + 'px';    
67                         }
68                     }
69                 },30);
70             }
71         </script>
72     </body>
73 </html>

 效果:

原文地址:https://www.cnblogs.com/panda-ling/p/6699852.html