//擷取樣式值function getStyle(obj, attr){if( obj.currentStyle) //IE{return obj.currentStyle[attr];} else //Chrome、 FF{return getComputedStyle(obj, false)[attr];}}//傳入參數:運動目標,運動參數鍵值對(json),串連函數function start_move(obj,json, fn_end ){//清除計時器clearInterval(obj.timer);obj.timer = setInterval(function(){var bStop = true;//判斷是否該停止運動//依次從json中取出各個屬性for( var attr in json){var cur = 0; //記錄屬性的當前//擷取屬性的當前值if( attr == "opacity" ){//保證cur是個整數cur = Math.round(parseFloat(getStyle(obj, attr)*100));} else {cur = parseInt(getStyle(obj, attr));}//計算速度var speed = ( json[attr] - cur) / 6;speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);//判斷是否停止運動if( cur != json[attr] )//如果當前值不等於目標值{bStop = false;//更改obj屬性if( attr == "opacity" ){obj.style.filter = "alpha(opacity:" + cur + speed + ")";obj.style.opacity = (cur + speed) / 100;}else {obj.style[attr] = cur + speed + "px";}}}if( bStop){clearInterval(obj.timer);//清除計時器if( fn_end ){//調用串連函數fn_end();}}});}
CurrentStyle 對象(IE相容):代表了在全域樣式表、內嵌樣式和 HTML 標籤屬性中指定的對象格式和樣式。
getComputedStyle 函數:Chrome和FF相容,擷取元素樣式。
可以彌補style的不足,但是。同currentStyle作用相同,但是。
<!DOCTYPE HTML><html><head><title>Test Move</title><meta charset="utf-8"/><script type="text/javascript" src="move.js"></script></head><style type="text/css">#div1 {left: 40px;top: 40px;width: 20px;height: 20px;position: absolute; background: red;}</style><body><div id="div1"></div><input type="button" id="button" value="Move"></button></body></html><script type="text/javascript">window.onload = function(){var oButton = document.getElementById("button");var oDiv = document.getElementById("div1");function move_button_back(){start_move( oButton, {height: 20, width: 40});}function move_div_back(){start_move( oDiv, {left: 40, height: 20, width: 20});}oButton.onclick = function() {start_move(oButton, {width: 300, height: 300}, move_button_back);start_move(oDiv, {left: 300, width: 200, height: 80}, move_div_back);}}</script>
運行效果:
參考:http://hi.baidu.com/lepharye/item/c36d3ba9ab3a919c14107344