Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)...

Here is the code I have:

    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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
378 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...