功能描述:一个标题的显示要限制长度,比如150px,多余的用三个省略号替代。代码如下
 问题是,如果有100个标题,循环执行下面的代码,在IE10里面太慢了,而且很奇怪,第一次是2秒多,后面依次递减,一直到最后一个几毫秒。但是在chrome里面速度特别快每一个都是1毫秒。
 后来,我大约发现,问题在于divTemp.innerText = nodeName;var length = divTemp.clientWidth;这里。可能不断填进去的文本,撑开隐藏的div,这个时候是同步的,所以得到新的宽度的时候需要时间,但该如何解决呢,在IE10?发现一个新的线索,就是当前页面是在iframe里面的,如果单独拿出来,执行,速度很快的,都是1毫秒或者0毫秒,怎么办? function getShortName(d) {
var now_time = new Date();
    var nodeName = d.name;
 
    var divTemp = document.getElementById("divHidden");
    divTemp.innerText = nodeName;
    var length = divTemp.clientWidth;
    if (length <= 150) {
        return nodeName;
    }
 
    var len = nodeName.length;
    var currentString = "";
    var previousString = nodeName.substring(0,19);
    for (index = 30; index < len; index++) {
        currentString = previousString + nodeName.substring(index, index + 1);
        divTemp.innerHTML = currentString + "...";
        length = divTemp.clientWidth;
        if (length > 150) {
            previousString += "...";            
            break;
        }
        previousString = currentString;
    }
     
var now_time2 = new Date();
var gap_time = now_time2.getTime() - now_time.getTime();
 
console.log(d.name + "   " + gap_time);
    return previousString;
}

解决方案 »

  1.   


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title> new document </title>
    <style type="text/css">
    .aa {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width:150px;
    }
    </style>
    </head>
    <body>
    <div class="aa">
    功能描述:一个标题的显示要限制长度,比如150px,多余的用三个省略号替代。
    </div>
    </body>
    </html>
      

  2.   

    这个用css做最好不过了,何必动刀js。
    关键css,text-overflow + white-space + overflow,得到的效果就是超出宽度自动截取+三个点。
    兼容IE6+,webkit,mozilla。
    .fn-ellipsis{
      text-overflow: ellipsis;overflow: hidden;white-space: nowrap;
    }
    .title{
      font-size:16px;
      font-weight:bold;
      width:150px;
      line-height: 30px;
    }<div class="title fn-ellipsis">JS的速度特别慢,求解,谢谢!JS的速度特别慢,求解,谢谢!</div>
      

  3.   


    firefox几?在我的记忆中,ellipsis早就可以放心大胆的用了,只有opera是不支持的,要用-o-text-overflow,firefox绝对支持。
    话说opera本来用的人就少,现在opera投奔谷歌内核了,完全可以忽略。