使用基于像素宽度的jQuery截断文本

nov*_*von 16 javascript jquery

我正在尝试使用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 + '&hellip;');
    } 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)

关于我做错了什么的任何想法?如果有更快的方法(即冒泡排序),这也会很棒.

谢谢!

jos*_*736 33

为什么不使用CSS来指定你将这个字符串放入的元素的宽度,而不是将其与脚本一起攻击?你可以用text-overflow它告诉浏览器它应该用省略号截断.

.truncated { display:inline-block; max-width:100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
Run Code Online (Sandbox Code Playgroud)

text-overflow是一个CSS3声明,但在IE 6 +,WebKit 312.3+(Safari 1.3 +/Chrome)和Opera 9+(版本<10.7需要-o-text-overflow声明)中受支持.

请注意,这在Firefox中未实现,直到7.0,并且不到4%的Firefox用户仍在使用旧版本(大多数是3.6).在旧版本中,您的文本仍将被截断,不会呈现省略号.如果你担心这一小组用户,你可以使用这个jQuery插件,它在IE/WebKit/Opera /Firefox≥7中什么都不做,但会text-overflow在Firefox≤6中模拟.

  • 请注意,除非使用空格:nowrap,否则文本溢出:省略号不起作用.也就是说,当您希望文本在其框中包装时,您无法使用它. (5认同)
  • 乐完美.谢谢 (2认同)

Dan*_*ett 3

在这一行:

smaller_text = smaller_text.substr(0, (smaller_text-1));

你可能有意

smaller_text = smaller_text.substr(0, (smaller_text.length-1));

这能解决问题吗?