用 CSS 截断长字符串:可行吗?

发布于 2024-07-18 09:13:31 字数 774 浏览 4 评论 0原文

有没有什么好方法可以用纯 HTML 和 CSS 截断文本,以便动态内容可以适合固定宽度和高度的布局?

我一直在服务器端截断逻辑宽度(即盲目猜测的字符数),但由于“w”比“i”宽,这往往不是最理想的,而且要求我重新猜测(并不断调整)每个固定宽度的字符数。 理想情况下,截断将发生在浏览器中,浏览器知道渲染文本的物理宽度。

我发现 IE 有一个 text-overflow: ellipsis 属性,它完全符合我的要求,但我需要它是跨浏览器的。 此属性似乎是(某种程度上?)标准,但 Firefox 不支持。 我发现各种 基于溢出的解决方法:隐藏,但它们要么不显示省略号(我希望用户知道内容被截断),要么一直显示它(即使内容没有被截断)。

有谁有一种在固定布局中适合动态文本的好方法,或者服务器端按逻辑宽度的截断是否像我现在要得到的那样好?

Is there any good way of truncating text with plain HTML and CSS, so that dynamic content can fit in a fixed-width-and-height layout?

I've been truncating server-side by logical width (i.e. a blindly-guessed number of characters), but since a 'w' is wider than an 'i' this tends to be suboptimal, and also requires me to re-guess (and keep tweaking) the number of characters for every fixed width. Ideally the truncation would happen in the browser, which knows the physical width of the rendered text.

I've found that IE has a text-overflow: ellipsis property that does exactly what I want, but I need this to be cross-browser. This property seems to be (somewhat?) standard but isn't supported by Firefox. I've found various workarounds based on overflow: hidden, but they either don't display an ellipsis (I want the user to know the content was truncated), or display it all the time (even if the content wasn't truncated).

Does anyone have a good way of fitting dynamic text in a fixed layout, or is server-side truncation by logical width as good as I'm going to get for now?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

听你说爱我 2024-07-25 09:13:31

更新: 从 Firefox 7(2011 年 9 月 27 日发布)开始,现在支持text-overflow: ellipsis。 耶! 我原来的回答如下,作为历史记录。

Justin Maxwell 拥有跨浏览器 CSS 解决方案。 但它确实有一个缺点,即不允许在 Firefox 中选择文本。 请查看他在 Matt Snider 博客上发表的客座文章,了解有关以下内容的完整详细信息这是如何运作的。

请注意,此技术还会阻止使用 Firefox 中的 innerHTML 属性更新 JavaScript 中的节点内容。 请参阅本文末尾的解决方法。

CSS

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}

ellipsis.xml 文件内容

<?xml version="1.0"?>
<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
    <binding id="ellipsis">
        <content>
            <xul:window>
                <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
            </xul:window>
        </content>
    </binding>
</bindings>

更新节点内容

以适用于的方式更新节点内容Firefox 使用以下内容:

var replaceEllipsis(node, content) {
    node.innerHTML = content;
    // use your favorite framework to detect the gecko browser
    if (YAHOO.env.ua.gecko) {
        var pnode = node.parentNode,
            newNode = node.cloneNode(true);

        pnode.replaceChild(newNode, node);
    }
};

请参阅 Matt Snider 的帖子,了解如何使用这有效

Update: text-overflow: ellipsis is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.

Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.

Note this technique also prevents updating the content of the node in JavaScript using the innerHTML property in Firefox. See the end of this post for a workaround.

CSS

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}

ellipsis.xml file contents

<?xml version="1.0"?>
<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
    <binding id="ellipsis">
        <content>
            <xul:window>
                <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
            </xul:window>
        </content>
    </binding>
</bindings>

Updating node content

To update the content of a node in a way that works in Firefox use the following:

var replaceEllipsis(node, content) {
    node.innerHTML = content;
    // use your favorite framework to detect the gecko browser
    if (YAHOO.env.ua.gecko) {
        var pnode = node.parentNode,
            newNode = node.cloneNode(true);

        pnode.replaceChild(newNode, node);
    }
};

See Matt Snider's post for an explanation of how this works.

┊风居住的梦幻卍 2024-07-25 09:13:31

2014 年 3 月:使用 CSS 截断长字符串:关注浏览器支持的新答案

上的演示http://jsbin.com/leyukama/1/(我使用jsbin,因为它支持旧版本的IE)。

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

-ms-text-overflow CSS 属性不是必需的:它是 text-overflow CSS 属性的同义词,但 IE 6 到 11 版本已经支持 text-overflow CSS 属性。

已在 Windows 操作系统上成功测试(在 Browserstack.com 上),适用于 Web 浏览器:

  • IE6 至 IE11
  • Opera 10.6、Opera 11.1、Opera 15.0、Opera 20.0
  • Chrome 14、Chrome 20、Chrome 25
  • Safari 4.0、Safari 5.0、Safari 5.1
  • Firefox 7.0、Firefox 15

Firefox:正如Simon Lieschke(在另一个答案中)所指出的,Firefox仅从Firefox 7(2011年9月27日发布)开始支持text-overflow CSS属性。

我在 Firefox 3.0 和 Firefox 3.0 上仔细检查了此行为。 Firefox 6.0(不支持文本溢出)。

需要在 Mac OS Web 浏览器上进行一些进一步的测试。

注意:您可能希望在应用省略号时在鼠标悬停时显示工具提示,这可以通过 javascript 完成,请参阅以下问题:HTML 文本溢出省略号检测HTML - 如何仅在激活省略号时显示工具提示

资源:

2014 March: Truncating long strings with CSS: a new answer with focus on browser support

Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.

Successfully tested (on Browserstack.com) on Windows OS, for web browsers:

  • IE6 to IE11
  • Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
  • Chrome 14, Chrome 20, Chrome 25
  • Safari 4.0, Safari 5.0, Safari 5.1
  • Firefox 7.0, Firefox 15

Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).

I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).

Some further testing on a Mac OS web browsers would be needed.

Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated

Resources:

許願樹丅啲祈禱 2024-07-25 09:13:31

如果您同意 JavaScript 解决方案,可以使用 jQuery 插件以跨浏览器的方式执行此操作 - 请参阅 http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

爱的十字路口 2024-07-25 09:13:31

好的,Firefox 7 实现了 text-overflow: ellipsis 以及 text-overflow: "string"。 最终版本计划于 2011 年 9 月 27 日发布。

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

写给空气的情书 2024-07-25 09:13:31

该问题的另一个解决方案可能是以下一组 CSS 规则:

.ellipsis{
 white-space:nowrap;
 overflow:hidden;
}

.ellipsis:after{
  content:'...';
}

上述 CSS 的唯一缺点是,无论文本是否溢出容器,它都会添加“...”。 不过,如果您有一堆元素并且确定内容会溢出,那么这将是一组更简单的规则。

我的两分钱。 向 Justin Maxwell 的原创技术致敬

Another solution to the problem could be the following set of CSS rules:

.ellipsis{
 white-space:nowrap;
 overflow:hidden;
}

.ellipsis:after{
  content:'...';
}

The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.

My two cents. Hats off to the original technique by Justin Maxwell

把时间冻结 2024-07-25 09:13:31

截至 2022 年,有一种新方法可以完成该任务,这就是 CSS 规则 line-clamp,它基本上告诉应保留多少行,其余所有行将被修剪。 下面是一个示例,您可以在其中拖动角并试验 div 的尺寸。

  #resizable { 
  width: 400px; 
  height: 150px; 
  padding: 0 20px; 
  }
  
.wrapper {
border: 1px solid #dddddd;
background: #ffffff;
color: #333333;
position: relative;
}

.slider-text-wrapper p, .slider-text-wrapper .h1 {
    width: 100%;
    word-break: break-all;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -ms-box-orient: vertical;
    box-orient: vertical;
    -webkit-line-clamp: 4;
    -moz-line-clamp: 4;
    -ms-line-clamp: 4;
    line-clamp: 4;
    overflow: hidden;
}
.slider-text-wrapper .h1 {
    -webkit-line-clamp: 2;
    -moz-line-clamp: 2;
    -ms-line-clamp: 2;
    line-clamp: 2;
    font-size: 20px;
    margin: 10px 0;
}
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">

  
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
  
  <script>
  $( function() {
    $( "#resizable" ).resizable();
  } );
  </script>
  
<div id="resizable" class="ui-widget-content wrapper">
<div class="slider-text-wrapper">
<p class="h1">Example headline with surplus of words without any meaning, for just mere demonstration of html and css</p>
<p class="slider-text-intro">Some representative placeholder content for the first slide of the carousel. Some representative placeholder content for the first slide of the carousel. Some representative placeholder content for the first slide of the carousel. Some representative placeholder content for the first slide of the carousel.</p>
</p>
</div>

As of 2022, there is a new approach to that task, this is CSS rule line-clamp, which basically tells how many lines should be kept and all the rest will be trimmed. Below is an example, where you can drag the corner and experiment with dimensions of the div.

  #resizable { 
  width: 400px; 
  height: 150px; 
  padding: 0 20px; 
  }
  
.wrapper {
border: 1px solid #dddddd;
background: #ffffff;
color: #333333;
position: relative;
}

.slider-text-wrapper p, .slider-text-wrapper .h1 {
    width: 100%;
    word-break: break-all;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -ms-box-orient: vertical;
    box-orient: vertical;
    -webkit-line-clamp: 4;
    -moz-line-clamp: 4;
    -ms-line-clamp: 4;
    line-clamp: 4;
    overflow: hidden;
}
.slider-text-wrapper .h1 {
    -webkit-line-clamp: 2;
    -moz-line-clamp: 2;
    -ms-line-clamp: 2;
    line-clamp: 2;
    font-size: 20px;
    margin: 10px 0;
}
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">

  
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
  
  <script>
  $( function() {
    $( "#resizable" ).resizable();
  } );
  </script>
  
<div id="resizable" class="ui-widget-content wrapper">
<div class="slider-text-wrapper">
<p class="h1">Example headline with surplus of words without any meaning, for just mere demonstration of html and css</p>
<p class="slider-text-intro">Some representative placeholder content for the first slide of the carousel. Some representative placeholder content for the first slide of the carousel. Some representative placeholder content for the first slide of the carousel. Some representative placeholder content for the first slide of the carousel.</p>
</p>
</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文