简体   繁体   中英

Max string length of html element

I have some tweets which are being pulled in on my website, each tweet length is different, but I want to make sure they get displayed on one line all the time.

This is how they should appear:

twitter字符串长度

However, if the twitter length exceeds so many words it falls on to the next line and messes with the design.

My question here is to give this string or div? (Excuse my poor understanding) a max length? Then possibly if we reach the max string length to add a ellipsis (...) to the end of the string.

The idea in my head is something like if #div > 120 then shorten the string to 120 and add (...). Could someone help me make that happen? Not sure if javascript/jQuery is the way to go here? Thank you!

You can simply use CSS to do that without moving into any computations either in JS or jQuery.

Define a fixed width to the div element where you want to display your tweet and apply css class Ellipsis to that element:

.Ellipsis
{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Hope that helps

In Javascript you can use the substring method for this.

var value = "This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.";

function truncate(value, length){
   return value.substring(0,300);
}

alert(truncate(value,3000));

Working Example

I would use the slice() method:

var formatted_tweet = long_tweet.slice(0, 120) + "...";

Or in function form:

function trim(str, len) {
    return(str.slice(0, len) + "...");
}

var formatted_tweet = trim(long_tweet, 120);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM