很好地截断一个字符串以适合给定的像素宽度

时间:2008-11-12 01:42:03

标签: javascript text reference refactoring

有时你的字符串必须符合某个像素宽度。此功能尝试有效地执行此操作。请在下面发布您的建议或重构:)

function fitStringToSize(str,len) {
    var shortStr = str;
    var f = document.createElement("span");
    f.style.display = 'hidden';
    f.style.padding = '0px';
    document.body.appendChild(f);

    // on first run, check if string fits into the length already.
    f.innerHTML = str;
    diff = f.offsetWidth - len;

    // if string is too long, shorten it by the approximate 
    // difference in characters (to make for fewer iterations). 
    while(diff > 0)
    {
        shortStr = substring(str,0,(str.length - Math.ceil(diff / 5))) + '…';
        f.innerHTML = shortStr;
        diff = f.offsetWidth - len;
    }

    while(f.lastChild) {
        f.removeChild(f.lastChild);
    }
    document.body.removeChild(f);

    // if the string was too long, put the original string 
    // in the title element of the abbr, and append an ellipsis
    if(shortStr.length < str.length)
    {
        return '<abbr title="' + str + '">' + shortStr + '</abbr>';
    }
    // if the string was short enough in the first place, just return it.
    else
    {
        return str;
    }
}

更新: @下面的某些解决方案要好得多;请使用它。

更新2: 代码现已发布为gist;随意分叉并提交补丁:)

4 个答案:

答案 0 :(得分:22)

您的代码存在一些问题。

  • 为什么/ 5?字符的宽度取决于font-familyfont-size
  • 您必须在abbr标题中转义str(否则“将使代码无效)。
  • diff未声明,并以全局范围结束
  • substring不应该像那样工作。您使用的浏览器是什么?
  • hidden不是style.display的有效值。要隐藏它,您应该使用值none,但浏览器不会计算offsetWidth。请改用style.visibility="hidden"
  • 寻找合适的长度是非常低效的。
  • 必须逃脱&lt;/abbr&gt;

我为您重新编写了它并添加了className,因此您可以使用样式设置font-familyfont-size。 Fooz先生建议您使用鼠标悬停来显示整个字符串。这是没有必要的,因为现代浏览器为你做这件事(用FF,IE,Opera和Chrome测试)

    function fitStringToSize(str,len,className) {
    var result = str; // set the result to the whole string as default
    var span = document.createElement("span");
    span.className=className; //Allow a classname to be set to get the right font-size.
    span.style.visibility = 'hidden';
    span.style.padding = '0px';
    document.body.appendChild(span);


    // check if the string don't fit 
    span.innerHTML = result;
    if (span.offsetWidth > len) {
        var posStart = 0, posMid, posEnd = str.length;
        while (true) {
            // Calculate the middle position
            posMid = posStart + Math.ceil((posEnd - posStart) / 2);
            // Break the loop if this is the last round
            if (posMid==posEnd || posMid==posStart) break;

            span.innerHTML = str.substring(0,posMid) + '&hellip;';

            // Test if the width at the middle position is
            // too wide (set new end) or too narrow (set new start).
            if ( span.offsetWidth > len ) posEnd = posMid; else posStart=posMid;
        }
        //Escape
        var title = str.replace("\"","&#34;");
        //Escape < and >
        var body = str.substring(0,posStart).replace("<","&lt;").replace(">","&gt;");
        result = '<abbr title="' + title + '">' + body + '&hellip;<\/abbr>';
    }
    document.body.removeChild(span);
    return result;
    }

编辑: 在进行测试时,我发现了一些错误。

  • 我使用了Math.ceil代替了Math.floor 意图<(我责备这个 英语不是我的母语 语言)

  • 如果输入字符串有html标签 然后结果将是未定义的 (截断标签是不好的 中间或留下开放的标签)

改进:

  • 转义复制到所有地方的范围的字符串。您仍然可以使用html-entities,但不允许使用任何标记(>while将会显示)
  • 重写了fitStringToWidth - 声明(它是一个 快一点,但主要原因 是摆脱那个错误 导致额外的轮次和摆脱 破裂声明)
  • 将该功能重命名为function fitStringToWidth(str,width,className) { // str A string where html-entities are allowed but no tags. // width The maximum allowed width in pixels // className A CSS class name with the desired font-name and font-size. (optional) // ---- // _escTag is a helper to escape 'less than' and 'greater than' function _escTag(s){ return s.replace("<","&lt;").replace(">","&gt;");} //Create a span element that will be used to get the width var span = document.createElement("span"); //Allow a classname to be set to get the right font-size. if (className) span.className=className; span.style.display='inline'; span.style.visibility = 'hidden'; span.style.padding = '0px'; document.body.appendChild(span); var result = _escTag(str); // default to the whole string span.innerHTML = result; // Check if the string will fit in the allowed width. NOTE: if the width // can't be determined (offsetWidth==0) the whole string will be returned. if (span.offsetWidth > width) { var posStart = 0, posMid, posEnd = str.length, posLength; // Calculate (posEnd - posStart) integer division by 2 and // assign it to posLength. Repeat until posLength is zero. while (posLength = (posEnd - posStart) >> 1) { posMid = posStart + posLength; //Get the string from the beginning up to posMid; span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;'; // Check if the current width is too wide (set new end) // or too narrow (set new start) if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid; } result = '<abbr title="' + str.replace("\"","&quot;") + '">' + _escTag(str.substring(0,posStart)) + '&hellip;<\/abbr>'; } document.body.removeChild(span); return result; }

第2版:

{{1}}

答案 1 :(得分:3)

快速浏览一下,它对我来说很好看。以下是一些小建议:

  • 使用二进制搜索来查找最佳大小而不是线性大小。

  • (可选)添加鼠标悬停,以便工具提示提供完整的字符串。

答案 2 :(得分:2)

你可以写相同的功能,但适合div的宽度和高度?我有一个固定宽度和高度的div,我需要从数据库中放置文本。如果文字对于div来说太大了,我想在最后剪切它并广告...可能?谢谢

编辑: 我为我的问题找到了JS解决方案:

<p id="truncateMe">Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Aenean consectetuer. Etiam venenatis. Sed ultricies, pede sit
amet aliquet lobortis, nisi ante sagittis sapien, in rhoncus lectus
mauris quis massa. Integer porttitor, mi sit amet viverra faucibus,
urna libero viverra nibh, sed dictum nisi mi et diam. Nulla nunc eros,
convallis sed, varius ac, commodo et, magna. Proin vel
risus. Vestibulum eu urna. Maecenas lobortis, pede ac dictum pulvinar,
nibh ante vestibulum tortor, eget fermentum urna ipsum ac neque. Nam
urna nulla, mollis blandit, pretium id, tristique vitae, neque. Etiam
id tellus. Sed pharetra enim non nisl.</p>

<script type="text/javascript">

var len = 100;
var p = document.getElementById('truncateMe');
if (p) {

  var trunc = p.innerHTML;
  if (trunc.length > len) {

    /* Truncate the content of the P, then go back to the end of the
       previous word to ensure that we don't truncate in the middle of
       a word */
    trunc = trunc.substring(0, len);
    trunc = trunc.replace(/\w+$/, '');

    /* Add an ellipses to the end and make it a link that expands
       the paragraph back to its original size */
    trunc += '<a href="#" ' +
      'onclick="this.parentNode.innerHTML=' +
      'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
      '...<\/a>';
    p.innerHTML = trunc;
  }
}

</script>

出于我的目的,我从...中删除了链接,因为我的页面上有另一个包含完整文本的标签。

答案 3 :(得分:1)

幸运的是,CSS3 text-overflow最终应该照顾到这一点。

如果有人使用ASP.NET并且对服务器端解决方案感兴趣,请查看此博客文章:

http://waldev.blogspot.com/2010/09/truncate-text-string-aspnet-fit-width.html

相关问题