1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> 7 div { 8 50px; 9 height: 50px; 10 background: red; 11 border: 1px solid red; 12 margin-top: 10px; 13 } 14 </style> 15 </head> 16 <body> 17 <div></div> 18 <div></div> 19 <div></div> 20 <script> 21 var odiv = document.getElementsByTagName('div'); 22 //var timer = null; 23 var target = 300; 24 var target1 = 50 for (let i = 0; i < odiv.length; i++) { odiv[i].onmouseover = function() { clearInterval(odiv[i].timer); 25 odiv[i].timer = setInterval(function() { 26 var _cur = parseInt(getStyle(odiv[i], "width")); 27 var speed = Math.ceil((target - _cur) / 8); 28 odiv[i].style.width = _cur + speed + "px"; 29 if (speed == 0) { 30 clearInterval(odiv[i].timer); 31 } 32 }, 20); 33 34 } 35 odiv[i].onmouseout = function() { 36 clearInterval(odiv[i].timer); 37 odiv[i].timer = setInterval(function() { 38 var _cur = parseInt(getStyle(odiv[i],"width")); 39 var speed = Math.floor((target1 - _cur) / 8); 40 odiv[i].style.width = _cur + speed + "px"; 41 if (speed == 0) { 42 clearInterval(odiv[i].timer); 43 } 44 }, 20); 45 } 46 } 47 //有一种方法既能取到行内样式又能取到非行内样式 48 function getStyle(obj,attr) { 49 if (window.getComputedStyle) { 50 return getComputedStyle(obj,null)[attr]; 51 } 52 return obj.currentStyle[attr]; 53 } 54 </script> 55 </body> 56 </html>