我正在尝试使用jquery编写一个快速函数来计算html页面上字符串的像素宽度,然后截断字符串直到达到理想的像素宽度...
但是它不起作用(文本没有截断)......
这是我的代码:
function constrain(text, original, ideal_width){
var temp_item = ('<span class="temp_item" style="display:none;">'+ text +'</span>');
$(temp_item).appendTo('body');
var item_width = $('span.temp_item').width();
var ideal = parseInt(ideal_width);
var smaller_text = text;
while (item_width > ideal) {
smaller_text = smaller_text.substr(0, (smaller_text-1));
$('.temp_item').html(text);
item_width = $('span.temp_item').width();
}
var final_length = smaller_text.length;
if (final_length != original) {
return (smaller_text + '…');
} else {
return text;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我从页面调用它的方式:
$('.service_link span:odd').each(function(){
var item_text = $(this).text();
var original_length = item_text.length;
var constrained = constrain(item_text, original_length,175);
$(this).html(constrained);
}); …
Run Code Online (Sandbox Code Playgroud) 我需要根据每个浏览器更改一个值,因为它们都以不同的方式呈现.
if (navigator.appName == 'Netscape'){
top = 17;
}
Run Code Online (Sandbox Code Playgroud)
这很有效但不幸的是Firefox和Safari都显示为"Netscape"
我如何使用jQuery 1.3.2来检测所有这些?我jquery.support
现在找不到任何信息jquery.browser
.
谢谢!
在IE/firefox中,此函数中的while语句运行速度太慢(阻止页面加载4-5秒),但在safari中运行速度很快...
它测量页面上文本的像素宽度并截断,直到文本达到理想宽度:
function constrain(text, ideal_width){
$('.temp_item').html(text);
var item_width = $('span.temp_item').width();
var ideal = parseInt(ideal_width);
var smaller_text = text;
var original = text.length;
while (item_width > ideal) {
smaller_text = smaller_text.substr(0, (smaller_text.length-1));
$('.temp_item').html(smaller_text);
item_width = $('span.temp_item').width();
}
var final_length = smaller_text.length;
if (final_length != original) {
return (smaller_text + '…');
} else {
return text;
}
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以提高性能?我如何将其转换为冒泡排序功能?
谢谢!