【问题标题】:Get clamped (with ellipsis) textContent from textNode从 textNode 获取钳位(带省略号)textContent
【发布时间】:2016-08-24 11:49:09
【问题描述】:

如何从 javascript 中的节点获取钳制文本?见以下代码:

console.log(document.getElementById("text1").textContent);
// prints "This is a long text"


console.log(document.getElementById("text2").textContent);
// prints "This is a long text as well"
// expected "This is a long text a..."
.longtext {
    width: 140px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
<div id="text1">This is a long text</div>
<div class="longtext" id="text2">This is a long text as well</div>

我想从 id 为 text2 的元素中获取预期的 "This is a long text a..."

【问题讨论】:

    标签: javascript html css ellipsis


    【解决方案1】:

    我发现了类似的问题:How can I access the actual text that is displayed in a DIV when using CSS style overflow: hidden?

    简而言之:

    没有简单的方法可以做到这一点。您必须根据 div 大小、字体大小、字体类型和 div 内的文本偏移量来计算在 DIV 中可以看到多少文本

    js怎么做省略号http://www.ruzee.com/blog/2007/08/ellipsis-or-truncate-with-dots-via-javascript

    【讨论】:

      【解决方案2】:

      运行您的代码 sn-p,它可以正常工作。 “文本溢出:省略号”按预期工作。这是工作代码的 JSFiddle 链接https://jsfiddle.net/qx5mL548/

      不明白您遇到了什么样的问题。你可以试试这个代码,如果它有效,请告诉我:

      <html>
      <head>Ellipsis</head>
      <style>
             .longtext {
                 width: 140px;
                 overflow: hidden;
                 white-space: nowrap;
                 text-overflow: ellipsis;
              }
          </style>
          <body>
              <div id="text1">This is a long text</div>
              <div class="longtext" id="text2">This is a long text as well</div>  
          </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-26
        • 2014-02-01
        • 2022-12-21
        • 2016-09-29
        • 2019-09-01
        • 2019-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多