I have multiple images on a page with the owner's name below it. This is printed by PHP. Some of the names happen to be quite long (which is messing up the page layout). I could very well truncate them inside PHP, but I decided to go with JS instead.
Here is what I'm doing:
$(document).ready(function() {
truncateNames(".users .a", 50);
}
function truncateNames(usernameID, maxChars){
$(usernameID).each(function() {
var longName = $(this).text();
if(longName.length > maxChars){
$(this).html(longName.trunc(maxChars));
}
});
}
// Taken from another question at http://goo.gl/fY4s4. Thanks KooiInc!
String.prototype.trunc =
function(n,useWordBoundary){
var toLong = this.length>n,
s_ = toLong ? this.substr(0,n-1) : this;
s_ = useWordBoundary && toLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
return toLong ? s_ + '…' : s_;
};
This works alright. But the problem is that I can see the long names for a few seconds before they are truncated. This also makes the messed up layout visible because of the long names, which auto fixes once names are truncated.
How can this be fixed?
答案 0 :(得分:4)
CSS:
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
SASS:
@mixin text-truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
答案 1 :(得分:1)
JavaScript可能不是这里的方法,因为在手动截断所有文本之前,您必须等待文档加载。我建议使用以下CSS解决方案:
div.ellipsize {
width: 200px;
border: 1px solid #000;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

<div class="ellipsize">Long text that's gonna get cut off</div>
&#13;