這是我的代碼的簡化,並解釋版本:使用Javascript/jQuery的文字動畫性能緩慢
var ptext=parr.find('div.ptext'); //Text Container
var pt=ptext.html(); //Text Container's string
var pdv=[pt.split(" ")]; //Text Container's array of words
pdv.push(pdv[0].length); //Write also the number of words
var ht=hp.html(); //Text Container's new string
var hdv=[ht.split(" ")]; //Text Container's new array of words
hdv.push(hdv[0].length); //New number of words
var kakaka=0; //If they begin with the same,
for (var j=0;j<hdv[0].length;j++){ //Animate only from the position
if (hdv[0][j]==pdv[0][j]) //where they differ
kakaka+=2;
}
window.clearTimeout(ptext.data('curt')); //Clear current animation's interval
ptext.data('count',kakaka); //Set starting position
ptext.data('curt', //Set interval's var into object
window.setInterval((function (item,pdv,hdv,text_callback) {
return function() { //item = text obj, text_callback= callback function
var i=item.data('count');
i=(i==undefined)?0:1+i;
item.data('count',i); //increase counter
//first phase - remove old text
if (i<=pdv[1]) // go on
{
item.html((pdv[0].slice(0,pdv[1]-i)).join(' '));
} //if reached the position, add new text
else if (i<=pdv[1]+hdv[1])
{
item.html((hdv[0].slice(0,i-pdv[1])).join(' '));
} //if finish clear timeout and call callback
else {
item.data('count',0);
window.clearTimeout(item.data('curt'));
text_callback();
}
}
})(ptext,pdv,hdv,text_callback),8) //8 = supposed interval
);
}
它得到的話從DIV,迅速刪除它們一個接一個,然後用填充它新的文字。
它採用.setInterval()函數,這是應該每隔8ms回調。這在我的i5 CPU上運行得非常好,但是它在i3筆記本電腦上速度非常慢。
你能就如何提高性能一些建議嗎?
你爲什麼一個接一個地挑選它們?這個代碼在全局中做了什麼?我們可以在您的方法中建議替代方案 – Joseph
那麼它有一個說明文字中,一個長款,這是一個設計功能,使從一個描述過渡到另 - 一個字一個字。 – Anonymous
我會選擇一個更快,更少CPU密集的解決方案,只需將其應用於整個句子。您將瀏覽器推向了極限,如果用戶的體驗變慢,用戶不會關心您的酷炫功能。另外,你選擇變量名稱會讓我想逃跑尖叫。考慮使用一些對名稱更有意義的東西。 :) – jmort253