开发者

Truncating long strings with ellipsis via PHP or CSS in Firefox [duplicate]

开发者 https://www.devze.com 2023-02-17 14:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: text-overflow:ellipsis in Firefox 4?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

text-overflow:ellipsis in Firefox 4?

I have the same issue mentioned in Truncating long strings with CSS: feasible yet?. It's been nearly two years since that post, and Firefox still ignores the text-overflow: ellipsis; property.

My current solution is to truncate long strings in PHP like so:

if(strlen($some_string) > 30)
    $some_string = substr($some_string,0,30)."...";

That more or less works, but it doesn't look as nice or as accurate as text-overflow: ellipsis; in browsers that support it. The actual width of thirty characters varies since I'm not using a monospace font. The XML fix and jQuery plugins posted in the other thread appear to no longer work in Firefox either.

Is there currently 开发者_开发问答a way to do this in CSS that is browser independent? If not, is there a way to measure the width of a string given a font and font size in PHP so that I might more accurately place my ellipsis?


This answer might be useful for getting your output truncated to the nearest word, and then simply append a … (…) HTML entity onto the end of the output to get your final output.

As you've noticed there's not sufficiently wide browser support yet the CSS solution yet, and you've still got to worry about old browsers too.


It is a shame that all browsers don't handle the same CSS features. However, you could always do something like this using JavaScript (with help from jQuery).

Here's an example of how such a thing might look: http://jsfiddle.net/VFucm/

The basic idea is to turn your string into an array of words, like so:

var words = full.split(/\s+/g);

Loop through them and take the first N (in this case I chose 24) and push them into another array:

for (var i = 0; i < 24; i++) {
    short.push(words[i]);
}

Throw them back into the HTML element they came from:

$('.snip').html(short.join(" ") + ' <span class="expand">...</span>');

... here I added a "link" to expand the shortend text. It's made to look and act like a link using CSS. I also provided a function to replace the shortened text with the foll text again:

$('.expand').click(function() {
    $('.snip').html(full);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号