更新& lt; a>文本没有任何延迟

Updating <a> text without any lag

本文关键字:任何 延迟 lt 更新 文本      更新时间:2023-09-26

我在一个页面上有多个图像,下面是所有者的名字。这是由PHP打印的。有些名字很长(这打乱了页面布局)。我可以很好地在PHP中截断它们,但我决定用JS代替。

我是这样做的:

$(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_ + '&hellip;' : s_;
};

可以正常工作。但问题是,在被截断之前,我可以在几秒钟内看到长名称。这也使得混乱的布局可见,因为名字很长,一旦名字被截断,就会自动修复。

如何解决这个问题?

CSS:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

SASS:

@mixin text-truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

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>