左侧的文本溢出省略号

Text-overflow ellipsis on left side

本文关键字:溢出 省略号 文本      更新时间:2023-09-26

我有一个路径列表(由于缺乏更好的词,也许面包屑痕迹更好地描述了它们(。有些值太长而无法在其父值中显示,所以我使用 text-overflow: ellipsis .问题是重要信息在右侧,所以我希望省略号出现在左侧。像这样的东西 这个 ascii 艺术:

----------------------------
|first > second > third    |
|...second > third > fourth|
|...fifth > sixth > seventh|
----------------------------

请注意,第一行足够短,因此它保持左对齐,但其他两行太长,因此省略号显示在左侧。

我更喜欢仅CSS的解决方案,但如果无法避免,JS很好。如果该解决方案仅适用于Firefox和Chrome,那也没关系。

编辑:在这一点上,我正在寻找解决Chrome中的错误的方法,这些错误在混合RTL和LTR时阻止其正确呈现。这就是我从一开始就真正需要的,我只是没有意识到这一点。

像这样的东西怎么样 jsFiddle?它使用方向、文本对齐和文本溢出来获取左侧的省略号。根据MDN的说法,将来可能会用left-overflow-type值指定左侧的省略号,但它被认为是实验性的。

p {
  white-space: nowrap;
  overflow: hidden;
  /* "overflow" value must be different from "visible" */
  text-overflow: ellipsis;
  width: 170px;
  border: 1px solid #999;
  direction: rtl;
  text-align: left;
}
<p>first > second > third<br /> second > third > fourth > fifth > sixth<br /> fifth > sixth > seventh > eighth > ninth</p>​

我最终不得不破解并用JavaScript做一些事情。我希望有人能想出一个冰雹玛丽CSS解决方案,但如果不是因为Chrome错误,人们似乎只是投票给应该正确的答案。J08691可以因为他的工作而获得赏金

<html>
    <head>
        <style>
            #container {
                width: 200px;
                border: 1px solid blue;
            }
            #container div {
                width: 100%;
                overflow: hidden;
                white-space: nowrap;
            }
        </style>
        <script>
            function trimRows() {
                var rows = document.getElementById('container').childNodes;
                for (var i=0, row; row = rows[i]; i++) {
                    if (row.scrollWidth > row.offsetWidth) {
                        var textNode = row.firstChild;
                        var value = '...' + textNode.nodeValue;
                        do {
                            value = '...' + value.substr(4);
                            textNode.nodeValue = value;
                        } while (row.scrollWidth > row.offsetWidth);
                    }
                }
            }
        </script>
    </head>
    <body onload='trimRows();'>
    <div id="container" >
        <div>first > second > third</div>
        <div>second > third > fourth > fifth > sixth</div>
        <div>fifth > sixth > seventh > eighth > ninth</div>​
    </div>
    </body>
</html>

小提琴

为什么不直接使用direction:rtl;

这有点问题,但也许是朝着正确方向的方向

http://jsfiddle.net/HerrSerker/ZfbaD/50/

$('.container')
    .animate({'width': 450}, 4000)
    .animate({'width': 100}, 4000)
    .animate({'width': 170}, 4000)
.container {  
  white-space: nowrap;                   
  overflow: hidden;              /* "overflow" value must be different from "visible" */   
  text-overflow: ellipsis;  
    width:170px;
    border:1px solid #999;
    direction:rtl;
}  
.container .part {
  direction:ltr;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
    <span class="part">second</span> 
    <span class="part">&gt;</span> 
    <span class="part">third</span> 
    <span class="part">&gt;</span> 
    <span class="part">fourth</span> 
    <span class="part">&gt;</span> 
    <span class="part">fifth</span> 
    <span class="part">&gt;</span> 
    <span class="part">sixth</span>
</div>

这些解决方案解决了前面或后面的弱或中性双向字符(如/'~.等(被误解的问题(基本上是任何标点符号或特殊字符(。

CSS解决方案

结合使用:

  • directionrtl & ltr
  • unicode-bidibidi-override

p {
  direction: rtl;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap; /* or pre (e.g. preserve multiple spaces) */
}
span {
  direction: ltr;
  unicode-bidi: bidi-override; /* or isolate, isolate-override, embed */
}
<p><span>/path/to/a/very/long/file.name</span></p>

解决方案

另一种可能性是使用 <bdo> 双向文本覆盖元素:

p {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap; /* or pre (e.g. preserve multiple spaces) */
}
<bdo dir="rtl">
  <p>
    <bdo dir="ltr">/path/to/a/very/long/file.name</bdo>
  </p>
</bdo>

使用@Hemlocks,@Brian Mortenson和@Jimbo的解决方案,我构建了一个jQuery插件来解决这个问题。

我还添加了使用 .html(( 返回初始值的支持,而不是让它返回当前的 innerHTML。希望它对某人有用...

(function($) {
$.trimLeft = function(element, options) {
    var trim = this;
    var $element = $(element), // reference to the jQuery version of DOM element
         element = element;    // reference to the actual DOM element
    var initialText = element.innerHTML;
    trim.init = function() {
        overrideNodeMethod("html", function(){ return initialText; });
        trimContents(element, element);
        return trim;
    };
    trim.reset = function(){
        element.innerHTML = initialText;
        return trim;
    };
    //Overide .html() to return initialText.
    var overrideNodeMethod = function(methodName, action) {
        var originalVal = $.fn[methodName];
        var thisNode = $element;
        $.fn[methodName] = function() {
            if (this[0]==thisNode[0]) {
                return action.apply(this, arguments);
            } else {
                return originalVal.apply(this, arguments);
            }
        };
    };
    var trimContents = function(row, node){
        while (row.scrollWidth > row.offsetWidth) {
            var childNode = node.firstChild;
            if (!childNode)
                return true;            
            if (childNode.nodeType == document.TEXT_NODE){
                trimText(row, node, childNode);
            }
            else {
                var empty = trimContents(row, childNode);
                if (empty){
                    node.removeChild(childNode);
                }
            }
        };
    };
    var trimText = function(row, node, textNode){
        var value = ''u2026' + textNode.nodeValue;
        do {
            value = ''u2026' + value.substr(4);
            textNode.nodeValue = value;
            if (value == ''u2026'){
                node.removeChild(textNode);
                return;
            }
        }
        while (row.scrollWidth > row.offsetWidth);
    };
    trim.init();
};
$.fn.trimLeft = (function(options){
  var othat = this;
  var single = function(that){
      if (undefined == $(that).data('trim')) {
          var trim = new $.trimLeft(that, options);
          $(that).data('trim', trim);
          $(window).resize(function(){
              $(that).each(function(){
                    trim.reset().init();
              });
          });
       }   
   };
   var multiple = function(){
        $(othat).each(function() {
            single(this);
        });
    };
    if($(othat).length>1)
        multiple(othat);            
    else
        single(othat);
    //-----------        
    return this;
});

})(jQuery);

开始使用:

//Call on elements with overflow: hidden and white-space: nowrap 
$('#container>div').trimLeft();
//Returns the original innerHTML
console.log($('#test').html());

小提琴

使用稍微复杂的标记(使用 bdi-tag 和省略号的额外跨度(,我们可以在 CSS 中完全解决问题,根本不需要 JS——跨浏览器(IE、FF、Chrome(,包括将标点符号保留在右侧:

http://jsbin.com/dodijuwebe/1/edit?html,css,output

当然,这是一种黑客攻击,涉及伪元素的善良。但是,我们的团队一直在生产中使用此代码,我们没有任何问题。

唯一的警告是:行的高度需要固定,背景颜色需要明确知道(继承不起作用(。

如果你不关心这些文本的索引,你可以使用这种方法(它反转文本行(:

如果你的文本中有其他HTML元素,除了<br>你需要做一些安排来使用这种方法。

网页代码:

<p>first > second > third<br/>
second > third > fourth <br>
fifth > sixth > seventh</p>

CSS代码:

p{
  overflow: hidden;
  text-overflow: ellipsis;
  unicode-bidi: bidi-override;
  direction: rtl;
  text-align: left;
  white-space: nowrap;
  width: 140px;
}

JavaScript 代码

[].forEach.call(document.getElementsByTagName("p"), function(item) {
  var str = item.innerText;
  //Change the operators
  str = str.replace(/[<>]/g, function(char){ return ({"<" : ">", ">" : "<"})[char] });
  //Get lines
  var lines = str.split(/'n/);
  //Reverse the lines
  lines = lines.map(function(l){ return l.split("").reverse().join("") }); 
  //Join the lines
  str = lines.join("<br>");
  item.innerHTML = str;
});

斯菲德尔

根据您的编辑:

在这一点上,我正在寻找解决Chrome错误的方法 在文档混合 RTL 时阻止其正确呈现 和LTR。这就是我从一开始就真正需要的,我只是没有 意识到这一点。

您是否研究过 unicode-bidi css 属性(请参阅 Sitepoint 或 W3C(?实际上,我自己只是在最近的另一篇文章中了解到这一点。我的猜测是,您可能希望对那些与主站点相反的片段使用embed值。因此,在j08691的答案中,direction: rtlunicode-bidi: embed添加到CSS中。这应该可以解决您遇到的"混合 RTL 和 LTR"问题。

我将一些 JavaScript 放在一起来正则表达式三个项目,并在必要时添加省略号。这不会明确查看框中可容纳多少文本,但如果框已修复,这可能不是问题。

<style>
p {  
    white-space: nowrap;                     
    overflow: hidden;
    text-overflow: ellipsis; 
    width:170px;
    border:1px solid #999;
    direction:rtl;
    text-align:left;
} 
</style>
<p>first &gt; second &gt; third<br />
second &gt; third &gt; fourth &gt; fifth &gt; sixth<br />
fifth &lt; sixth &lt; seventh &lt; eighth &lt; ninth</p>
<script>
    var text = $( 'p' ).text(),
        split = text.split( ''n' ),
        finalStr = '';
    for( i in split ){
        finalStr = finalStr.length > 0 ? finalStr + '<br />' : finalStr;
        var match = /('w+'s?(<|>)?'s?){3}$/.exec( split[i] );
        finalStr = finalStr + ( split[i].length > match[0].length ? '...' : '' ) + match[0];
    }
    $( 'p' ).empty().html( finalStr );
</script>