[英]Moving pictures with Javascript
我的網站有問題,或者至少我認為有問題。 我使用一個非常簡單的幾乎遞歸的Javascript函數來移動兩張圖片。 但是,在我四歲的計算機上,這並不是一個平穩的動作。 我縮小了圖片的尺寸,但是...
該代碼不是遞歸的,因為我在兩次調用之間使用setTimeout。
代碼如下:(onload)
sImgArray = ["imgLaVera", "imgAlmanzor", "imgRosarito", "imgBaile"];
iImg = sImgArray.length - 1;
setTimeout('playShow(0,' + iImg + ')', 4000);
function playShow(iVisible, iImgs)
{
if( iVisible < iImgs )
iLeft = iVisible + 1;
else
iLeft = 0;
imgLeft = document.getElementById(sImgArray[iLeft]);
imgLeft.style.left = "-" + imgLeft.width + "px";
playMove(-imgLeft.width, iVisible, iImgs);
}
function playMove(i, iVisible, iImgs)
{
if( iVisible < iImgs )
iLeft = iVisible + 1;
else
iLeft = 0;
imgLeft = document.getElementById(sImgArray[iLeft]);
imgRight = document.getElementById(sImgArray[iVisible]);
if( i < 0 )
{
i = i + 5;
imgLeft.style.left = (i - 2) + "px";
imgRight.style.left = (i + imgLeft.width) + "px";
setTimeout('playMove(' + i + ', ' + iVisible + ',' + iImgs + ')', 75);
}
else
{
if( iVisible < iImgs )
iVisible = iVisible + 1;
else
iVisible = 0;
setTimeout('playShow(' + iVisible + ',' + iImgs + ')', 4000)
}
}
有什么建議么?
好像您每75毫秒前進一次動畫。 那是ca。 每秒13個步驟。 每秒至少需要24步才能平穩移動。 我建議33毫秒(每秒30步)或16毫秒(每秒60步)。 jQuery用於動畫的時間是16毫秒(jQuery非常擅長此操作)。
playMove
的以下設置將為您提供所需的內容:
i = i + 1;
setTimeout('playMove( ... )', 15);
您的動畫似乎呆滯,因為您很少更改圖像位置並且跳得很大 。 如果希望它更平滑 ,則應更頻繁地更改位置,但每一步中的像素要少一些。
Old: 5 px / 75 ms
New: 1 px / 15 ms
圖片的標題說明
如果您確實關心速度,請不要在每次調用渲染函數( playMove
)時都選擇元素。 在show
結束時,在調用setTimeout
之前執行此操作:
// select elements by their id and replace them in the array
for (var i = sImgArray.length; i--;) {
sImgArray[i] = document.getElementById( sImgArray[i] );
}
現在您可以簡單地寫
sImgArray[iLeft]
代替
document.getElementById(sImgArray[iLeft])
在playMove和playShow中。
其次,您應避免將函數作為文本參數傳遞,因為它們需要分別規避。
// GOOD
setTimeout(function() {
playShow(iVisible, iImgs);
}, 4000);
// BAD
setTimeout('playShow(' + iVisible + ',' + iImgs + ')', 4000)
第三,這就像我一生中看到的最丑陋的東西:
setTimeout('show.call(\'index\');', 6000);
不要使用this
引用將參數傳遞給函數。 這就是普通參數列表的用途。
setTimeout(function() {
show('index');
}, 4000);
然后,您的功能show
將變成這樣:
function show( page ) // pass string as an argument
{
if ( page == "index" )
{
// ...
我建議您使用一個庫來幫助您實現這一目標。 例如jQuery ,其中有一些示例: http : //api.jquery.com/animate/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.