0
首先:我嘗試尋找一個類似的問題,但真的不知道如何描述這個,而不是我如何在標題中做到這一點。所以如果在某個地方已經有解決方案,請告訴我。Javascript:帶參數的函數導致動畫滯後
我想了解OOP如何在JavaScript中工作。我有一些actionscript的經驗。爲了練習,我寫了這段代碼。當頁面加載時,它會使框從左向右移動。現在我想以這樣的方式重寫代碼,即使我想創建多個動畫框,我也不需要爲同一種動畫創建數百個函數。
這是我的舊代碼,它的工作:
<script>
var dx = 850;
var x = 0;
var y = 450;
function init() {
b = document.getElementById("box1");
moveIt();
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame OR
window.webkitRequestAnimationFrame OR
window.mozRequestAnimationFrame OR
window.oRequestAnimationFrame OR
window.msRequestAnimationFrame OR
function (/* function */ callback, /* DOMElement */ element)
{
window.setTimeout(callback, 1000/60);
};
})();
function moveIt() {
x += (dx - x) * 0.15;
b.style.left = x + "px";
b.style.top = y + "px";
requestAnimFrame(moveIt, b);
}
</script>
</head>
<body onload="init()">
<div style="width:50px;height:50px;background:blue;position:absolute;" id="box1"></div>
</body>
這是第二個版本,其中我試圖使動畫的功能更加動感。它似乎工作,但它似乎滯後,或者它根本不做動畫,我不確定,因爲它很難檢查。
<script>
function init() {
b = document.getElementById("box1");
moveIt(b, 0, 850, 0, 450);
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame OR
window.webkitRequestAnimationFrame OR
window.mozRequestAnimationFrame OR
window.oRequestAnimationFrame OR
window.msRequestAnimationFrame OR
function (/* function */ callback, /* DOMElement */ element)
{
window.setTimeout(callback, 1000/60);
};
})();
function moveIt(theobject, x, endx, y, endy) {
x += (endx - x) * 0.15;
y += (endy - y) * 0.15;
theobject.style.left = x + "px";
theobject.style.top = y + "px";
requestAnimFrame(moveIt(theobject, x, endx, y, endy), b);
}
</script>
</head>
<body onload="init()">
<div style="width:50px;height:50px;background:blue;position:absolute;" id="box1"></div>
</body>
由於我忙於瞭解這些事情,所以我對任何可以改進的地方都感到好奇。
這點樣-的。 – 2014-11-04 11:01:57
感謝您的回覆!我意識到if語句也會解決它。但不幸的是,這並沒有解決我的問題。我仍然看不到動畫,它從一開始就出現在其目的地上。 – GeirrBenayahu 2014-11-04 11:44:47
哦,哦。對不起,我沒有注意到按鈕!我的錯。 雖然現在嘗試了。但還是有滯後的。對你起作用嗎? – GeirrBenayahu 2014-11-04 11:58:09