![](/img/trans.png)
[英]How can I make this jQuery “shrink text” function more efficient? With binary Search?
[英]How can I make a jQuery function that shrinks a string using a binary search method?
我正在嘗試創建一個jQuery函數,它將一個字符串和一個固定的寬度作為輸入,然后通過二進制搜索方法(為了效率)“縮小”該文本,因此它不會超過固定寬度。
這是我到目前為止:
function constrain(text, ideal_width){
var temp = $('.temp_item');
temp.html(text);
var item_width = temp.width();
var ideal = parseInt(ideal_width);
var text_len_lower = 0;
var smaller_text = text;
var text_len_higher = text.length;
while (true) {
if (item_width > ideal) {
// make smaller to the mean of "lower" and this
text_len_higher = smaller_text.length;
smaller_text = text.substr(0, ((text_len_higher + text_len_lower)/2));
} else {
if (smaller_text.length >= text_len_higher) break;
// make larger to the mean of "higher" and this
text_len_lower = smaller_text.length;
smaller_text = text.substr(0, ((smaller_text.length + text_len_higher)/2));
}
temp.html(smaller_text);
item_width = temp.width();
}
var new_text = smaller_text + '…'
return new_text;
}
不幸的是,這會導致我的瀏覽器永遠無法完成“慢速腳本”。 Firebug指向jquery.js(版本1.3.2)的第1131行,這是“獨特的”jQuery實用程序,作為罪魁禍首。 然而,我並沒有在任何地方使用“獨特”。
我在這做錯了什么?
你可以連接一個javascript調試器並檢查崩潰的位置嗎? 使用Firebug與Firefox或MSVS與IE。 如果它如此猛烈地破壞調試器就會死掉,請逐步完成該功能,看看它到底有多遠。
根據上次評論進行更新:我認為您需要逐步完成代碼,看看它有多遠。 我會懷疑一些事情:
在設置新的內部文本后,可能尚未重新計算對象的寬度(或已變為無效)。 可能是更新的寬度直到稍后,當UI進行重新調整時才可用。
理論上這個循環應該總是終止,但它可能(特別是如果瀏覽器沒有正確地重新計算寬度)循環可以永遠繼續。
拆分內部文本時,您可能會拆分HTML標記,從而導致代碼插入格式錯誤的HTML,從而導致頁面布局中斷。
您正在嘗試實現已存在的內容:
CSS的text-overflow:ellipsis
屬性。 不幸的是,它只有IE支持,但jQuery插件為Firefox帶來了功能。 谷歌的“文字溢出:省略號火狐”因為我還沒有被允許發布鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.