【问题标题】:Optimizing text length of limited space优化有限空间的文本长度
【发布时间】:2013-08-10 01:04:59
【问题描述】:

我在固定宽度的 div 中显示不同字符和长度的文本字符串。我想在分配的空间中放置尽可能多的文本。我目前的做法是通过以下方式限制文本字符的数量

var n = //some number
string = string.substr(0,n);

这种方法的问题是不同的字符有不同的宽度,所以虽然它可以覆盖溢出,但它通常会留下未使用的空间。我尝试为包含的 div 赋予以下 css 属性。

div{
   width:200px
   white-space:nowrap
}

但是一旦超出宽度,文本仍然会换行到下一行。有人可以帮助我解决这个问题的好方法吗?

【问题讨论】:

标签: javascript string html width space


【解决方案1】:

你可以试试text-overflow

来自quirks mode

文本溢出仅在以下情况下起作用:

盒子有溢出而不是可见(溢出:可见文本只是从盒子里流出) 该框具有 white-space: nowrap 或类似的限制文本布局方式的方法。 (没有这个,文本会换到下一行)

风格变化:

div{
   width:200px;
   white-space:nowrap;
   overflow: hidden;
   text-overflow: ellipsis;
}

Working demo

【讨论】:

  • 感谢您的回复,您的 css 确实阻止了换行,但似乎没有提供任何宽度限制。
  • 也许有别的东西妨碍了。使用一个简单的 html 文档和一个 div,这对我有用。
【解决方案2】:

使用如下所述的方法计算文本的实际宽度:https://coderwall.com/p/kdi8ua

然后继续添加字符,直到宽度大于元素的宽度,然后删除 1。

这是链接到的网站的功能:

// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.html(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多