javascript 根据像素宽度截断字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26019875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:22:38  来源:igfitidea点击:

Truncate string based on pixel width

javascriptjqueryhtmlcss

提问by Michel Ayres

I'm trying to make a string fits in a determined area (td) without breaking line. The problem is: It needs to ...

我试图在不断线的情况下使字符串适合确定的区域 ( td)。问题是:它需要...

  • Fit while resizing
  • Fit in Nkinds of resolution
  • Add ...at the end when needed (and don't when not needed)
  • Accept the change of font-size, font-weight, and font-family
  • 调整大小时适合
  • 适合N各种分辨率
  • ...需要时添加在最后(不需要时不要添加)
  • 接受font-sizefont-weight、 和font-family


Based on the answers on Novon's question, I made the following code:

根据Novon's question的答案,我编写了以下代码:

CSS(// Just adding some styles to break the line)

CSS (// 只是添加一些样式来断行)

.truncated { display:inline-block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

jQuery(// Find all td that contains a .truncatedelement. Getting the real width (by removing the content and adding it again) of the td. Applying, if needed, minWidth on the td)

jQuery (// 查找包含.truncated元素的所有 td 。获取 的实际宽度(通过删除内容并再次添加)td。如果需要,在 上应用 minWidth td

jQuery('.truncated').closest('td').each(function() {
    var text = jQuery(this).text();
    var widthOriginal = jQuery(this).width();
    var widthEmpty = jQuery(this).text('').width();
    jQuery(this).text(text);
    if(widthOriginal >= widthEmpty){
        var width = (parseInt(widthEmpty) - 10) + 'px';
        jQuery(this).css('maxWidth', width);
        jQuery(this).text(text + '...');
    }
});

the result (as expected from the above code) is:

结果(如上述代码所预期的)是:

result

结果

but it should be:

但它应该是:

how it should be

应该如何



I was thinking, maybe try to find the first lineof the string and remove the rest but didn't find a way to do that (and it's a lot of "workaround" for my taste). Is there a better way to do that?

我在想,也许尝试找到line字符串的第一个并删除其余的字符串,但没有找到方法(并且根据我的口味,这是很多“解决方法”)。有没有更好的方法来做到这一点?

采纳答案by Caio Kawasaki

You can do it with pure CSS, see this link for reference:

您可以使用纯 CSS 来完成,请参阅此链接以供参考:

line clampin

线夹

Add those to your css:

将这些添加到您的 css 中:

.truncated {
  display: -webkit-box;
  -webkit-line-clamp: 1; // amount of line you want
  -webkit-box-orient: vertical;  
}

Or you can try clamp.js

或者你可以试试clamp.js

https://github.com/josephschmitt/Clamp.js

https://github.com/josephschmitt/Clamp.js

回答by Hugo Silva

Single line text truncation can be easily achieved using css text-overflowproperty, which is supported by all major browsers, including IE since version 6.

使用 csstext-overflow属性可以轻松实现单行文本截断,所有主要浏览器都支持该属性,包括自版本 6 起的 IE。

The thing is that text-overflowalone doesn't do much. It only defines what will happen when there istext overflowing the container. So in order to see results, we first need to make the text overflow, by forcing it to a single line. It is also important to set the overflowproperty of the container:

问题是,text-overflow仅凭这一点并没有多大作用。它只定义文本溢出容器会发生什么。所以为了看到结果,我们首先需要让文本溢出,强制它变成一行。设置overflow容器的属性也很重要:

.truncated {
    display: block;
    white-space: nowrap; /* forces text to single line */
    overflow: hidden;
    text-overflow: ellipsis;
}

jsFiddle example: https://jsfiddle.net/x95a4913/

jsFiddle 示例:https://jsfiddle.net/x95a4913/

text-overflow documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow

文本溢出文档:https: //developer.mozilla.org/en-US/docs/Web/CSS/text-overflow

回答by Francesco

text-overflow: ellipsis

seems a pure CSS solution http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

似乎是一个纯 CSS 解决方案 http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

回答by skobaljic

Wrap the text twice to achieve this:

将文本换行两次以实现此目的:

<style type="text/css">

.relative_wrap {
    height: 1em;
    position: relative;
}

.absolute_wrap {
    position: absolute;
    left: 0px;
    right: 0px;
    bottom: 0px;
    overflow: hidden;
    text-overflow: ellipsis;
    top: 0px;
    white-space: nowrap;
}

</style>


<table>
    <tbody>
        <tr>
            <td>
                <div class="relative_wrap">
                    <div class="absolute_wrap">
                            LONG TEXT HERE
                    </div>
                </div>
            </td>
        </tr>
    </tbody>
</table>

Since you use jQuery, it is easy:

由于您使用 jQuery,因此很容易:

$('.truncated').wrap('<div class="relative_wrap"><div class="absolute_wrap"></div></div>');

回答by Rick Hitchcock

If you set table layout to fixed and the tdoverflow as hidden, you could prepend an ellipsis as a float-right divwhen the td's scroll width is greater than its client width.

如果您将表格布局设置为 fixed 并且将td溢出设置为hidden,则divtd的滚动宽度大于其客户端宽度时,您可以在前面添加一个省略号作为浮动右侧。

Here's the CSS, which includes styles to prevent bleed-through on the table:

这是 CSS,其中包括防止表格渗漏的样式:

table {
  table-layout:fixed;
  white-space:nowrap;
  width:500px;
  border-spacing: 0px;
  border-collapse: separate;    
}

td {
  overflow:hidden;
  border:1px solid #ddd;
  padding:0px;
}

.hellip {
  padding-left:0.2em;
  float:right;
  background:white;
  position:relative;
}

jQuery:

jQuery:

$('td').each(function() {
  if($(this)[0].scrollWidth > $(this).width()) {
    $(this).prepend('<div class="hellip"">&hellip;</div>');
  }
});

Demo at: http://jsfiddle.net/5h798ojf/3/

演示:http: //jsfiddle.net/5h798ojf/3/