今天這篇文章主要簡述js如何經過改變屬性來實現動畫效果,好比經過定時器快速改變width, height, left, top等屬性,實現圖形在html的頁面上作勻速的運動。html
如今就有這樣的一個需求,定義2個不一樣背景顏色的物體,當點擊按鈕的時候,實現向左,向下勻速
運動。dom
關鍵語法:
1,獲取當前dom的指定屬性值動畫
function computedStyle(dom,attr) { if(getComputedStyle) { return getComputedStyle(dom,'')[attr] } else { return dom.currentStyle()[attr] //兼容IE } }
這個方法定義的目的是爲了獲取dom 屬性的值,例如:
dom: '<div width="30px"></div>',調用這個方法
computedStyle(dom,'width') 返回 30。code
2,定時器,返回這個定時器的惟一id標識htm
timerId = setInterval(function(){ },1000);
這個定時器的主要目的是爲了勻速改變dom的屬性的值get
示例:input
#box{ width: 100px; height: 100px; background: red; position:absolute; /*getComputedStyle 方法取屬性左邊的值'left' 爲800*/ left: 800px; top: 50px; } #box1{ width: 100px; height: 100px; background: blue; position:absolute; left: 900px; top: 50px; } <input type="button" id="button" value="開始運動"/> <div id="box">box</div> <div id="box1">box1</div> //封裝獲取id的方法 function $(id) { return document.getElementById(id); } //獲取計算後的屬性 attr='width' function computedStyle(dom,attr) { if(getComputedStyle) { return getComputedStyle(dom,'')[attr] } else { return dom.currentStyle()[attr] } } window.onload=function(){ var btn=$('button'); var box=$('box'); var box1=$('box1'); btn.onclick=function(){ animate(box,'left',100); animate(box1,'top',400); } function animate(dom,attr,target){ //多個元素一塊兒運動 每一個元素綁定一個屬性放當前運動的定時器 dom.timer=setInterval(function() { var current=parseInt(computedStyle(dom,attr)); var step=(target>current)?1:-1; /*目標大於當前值 +1 目標小於當前值-1*/ if(target==current) { // 若是等於100的時候退出,也是定時器退出的條件 dom.style[attr]=target+'px'; clearInterval(dom.timer); return false; } //改變位置 dom.style[attr]=(current+step)+'px'; //改變style的屬性,實現動畫 },10) //每10毫秒改變一次 } }