JS-運動架構

來源:互聯網
上載者:User

//擷取樣式值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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.