<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>window.getComputedStyle(div,null)</title> <style type="text/css"> *{margin:0;padding:0} </style> </head> <body> <div style="width: 100px; height: 100px; background: red; position: absolute;left: 0; top:0"></div> <script type="text/javascript"> //封装 function getStyle(elem,prop){ if(window.getComputedStyle){ //如果它存在的话(兼容谷歌) return window.getComputedStyle(elem,null)[prop];//prop作为参数字符串传进来,所有得中括号 }else{ return elem.currentStyle[prop]; //兼容IE } } var timer; var div = document.getElementsByTagName(‘div‘)[0] timer=setInterval(function(){ div.style.left=parseInt(getStyle(div,‘left‘))+1+"px";//注意:getStyle(div,‘left‘)打印出来是0px,所以用parseInt取整数 },10) div.onclick = function() { clearInterval(timer) } </script> </body> </html>
效果图: