使用基于像素宽度的jQuery截断文本 [英] Truncate text with jQuery based on pixel width

查看:116
本文介绍了使用基于像素宽度的jQuery截断文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jquery编写一个快速函数来计算html页面上字符串的像素宽度,然后截断字符串直到达到理想的像素宽度...

I'm trying to use jquery to write a fast function that calculates the pixel width of a string on a html page, then truncates the string until it reaches an ideal pixel width...

然而它不起作用(文本没有截断)......

However it's not working (the text doesn't truncate)...

这是我的代码:

    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;
    }
}

以下是我从页面调用它的方式:

Here's how I'm calling it from the page:

    $('.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);
});

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

Any ideas on what I'm doing wrong? If there is a way to do it faster (ie bubble sort), that would be great too.

谢谢!

推荐答案

为什么不用CSS来指定你将这个字符串放入的元素的宽度?您可以使用 text-overflow 告诉浏览器它应该用省略号截断。

Rather than hacking this together with script, why not just use CSS to specify the width of the element you're putting this string into? You can use text-overflow to tell the browser it should truncate with an ellipsis.

.truncated { display:inline-block; max-width:100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

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

text-overflow is a CSS3 declaration, but is supported in IE 6+, WebKit 312.3+ (Safari 1.3+/Chrome), and Opera 9+ (versions < 10.7 need the -o-text-overflow declaration).

请注意,这个在Firefox中未实现直到7.0,Firefox用户的低于4%仍然使用旧版本(大多数是3.6)。在旧版本中,您的文本仍将被截断,不会呈现省略号。如果您担心这一小组用户,可以使用此jQuery插件 ,在IE / WebKit / Opera / Firefox&ge中没有任何作用; 7,但将在Firefox&le中模拟 text-overflow ; 6。

Note that this was unimplemented in Firefox until 7.0, and under 4% of Firefox users are still using old versions (mostly 3.6). Your text will still be truncated in older versions, there just won't be an ellipsis rendered. If you're concerned about this small group of users, you can use this jQuery plugin, which does nothing in IE/WebKit/Opera/Firefox ≥ 7, but will emulate text-overflow in Firefox ≤ 6.

这篇关于使用基于像素宽度的jQuery截断文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆