javascript 使用链接截断 html 中的文本以显示更多/更少并将元素保留在里面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28334540/
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 08:48:38  来源:igfitidea点击:

Truncate text in html with link to show more / less and keep elements inside

javascriptjqueryhtmlcsstruncate

提问by Hans Ullrich

I found this fiddle here for truncating text in html from @iambriansreed

我在这里找到了这个小提琴,用于从@iambriansreed截断 html 中的文本

http://jsfiddle.net/iambriansreed/bjdSF/

http://jsfiddle.net/iambriansreed/bjdSF/

<p class="minimize">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text.</p>

jQuery(function(){

    var minimized_elements = $('p.minimize');

    minimized_elements.each(function(){    
        var t = $(this).text();        
        if(t.length < 100) return;

        $(this).html(
            t.slice(0,100)+'<span>... </span><a href="#" class="more">More</a>'+
            '<span style="display:none;">'+ t.slice(100,t.length)+' <a href="#" class="less">Less</a></span>'
        );

    }); 

    $('a.more', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).hide().prev().hide();
        $(this).next().show();        
    });

    $('a.less', minimized_elements).click(function(event){
        event.preventDefault();
        $(this).parent().hide().prev().show().prev().show();    
    });

});

Its from this post here on stackoverflow:

它来自stackoverflow上的这篇文章:

Truncate paragraph first 100 character and hide rest content of paragraph to show/hide rest contenct with more/less link

截断段落的前 100 个字符并隐藏段落的其余内容以显示/隐藏带有更多/更少链接的其余内容

The Problem is it only takes the plain text from the paragraph with .text but what if I want to truncate the text with its html elements like links, bold type and stuff. I tried adding a second variable which selects the text with elements:

问题是它只从带有 .text 的段落中获取纯文本,但是如果我想用它的 html 元素(如链接、粗体类型和其他东西)截断文本怎么办。我尝试添加第二个变量来选择带有元素的文本:

var h = $(this).html();

and adding it to the slice function:

并将其添加到 slice 函数中:

$(this).html(
        t.slice(0,100)+'<span>... </span><a href="#" class="more">More</a>'+
        '<span style="display:none;">'+ h.slice(100,h.length)+' <a href="#" class="less">Less</a></span>'
);

It kinda works but sometimes I get words double or cut because it does not count up (100 chars text vs 100 chars text with elements)

它有点工作,但有时我会得到双倍或减少的单词,因为它不计数(100 个字符文本与 100 个字符文本与元素)

So that post is 2 years old and I was wondering if there is any plugin or solution for my problem.

所以那个帖子已经 2 年了,我想知道是否有任何插件或解决方案可以解决我的问题。

best regards

最好的祝福

回答by Stefan

HTML5 provides the text-overflow: ellipsis;property.

HTML5 提供了该text-overflow: ellipsis;属性。

Append ellipsis when text overflows its containing element -Source: http://caniuse.com/#search=ellipsis

当文本溢出其包含元素时附加省略号 - 来源:http: //caniuse.com/#search=ellipsis

It is supported in all major browser.

所有主流浏览器都支持它。

With this you can just toggle the class on the container, and it will not overflow the space.

有了这个,您只需切换容器上的类,它就不会溢出空间。

 $(function() {
   $('div').click(function() {
     $(this).toggleClass('crop');
   });
 });
    #test {
      background: #eee;
      border: 1px dotted #ccc;
      margin: 1em;
    }
    .crop {
      white-space: nowrap;
      width: 12em;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 400px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" class="crop">Lorem Ipsum is simply <a href="orf.at">dummy</a> text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
  book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged</div>

In my opinion, this is a better solution for your problem, since counting it by characters can still destroy your layout, because different characters have different sizes. However, with a JS plugin you could only truncate by counting characters, with CSS you can truncate by the available space!

在我看来,这是您问题的更好解决方案,因为按字符计算仍然会破坏您的布局,因为不同的字符具有不同的大小。但是,使用 JS 插件您只能通过计算字符来截断,使用 CSS 您可以通过可用空间来截断!

Future Reading: With CSS, use “…” for overflowed block of multi-lines

未来阅读:使用 CSS,对多行溢出块使用“...”

回答by arendjr

I recently had the same problem and needed a solution that could work outside the DOM. I know there are a few libraries that solve this problem, but they all work through regular expression hacks and therefore cannot safely process all valid HTML.

我最近遇到了同样的问题,需要一个可以在 DOM 之外工作的解决方案。我知道有一些库可以解决这个问题,但它们都通过正则表达式黑客工作,因此不能安全地处理所有有效的 HTML。

So I made an HTML-aware clipping method: https://github.com/arendjr/text-clipper

所以我做了一个 HTML-aware 裁剪方法:https: //github.com/arendjr/text-clipper