截断可能包含或不包含HTML元素的段落文本的最快捷方法是什么? [英] What's the quickest way to truncate paragraph text that may or may not include HTML elements?

查看:85
本文介绍了截断可能包含或不包含HTML元素的段落文本的最快捷方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要截断可能包含或不包含HTML标记的段落文本。我正在寻找使用直接jQuery或vanilla javascript执行此操作的最有效方法。你可以在这里看到问题: http://jsfiddle.net/4BzpY/3/

I need to truncate paragraph text that may or may not include HTML tags. I'm looking for the most efficient way to do this with straight jQuery or vanilla javascript. You can see the problem here: http://jsfiddle.net/4BzpY/3/

var text = "This <a href=\"\">is</a> some text with a link";

var shortText = jQuery.trim(title).substring(0, 10).split(" ").slice(0, -1).join(" ") + "...";

alert(shortText );

截断的文本将位于可以动态展开以显示所有内容的段落元素中。在这种情况下,我不想剥离HTML标记,然后仅在完全展开时显示它们。 HTML应保持原样处于折叠和展开状态。

The truncated text will be in a paragraph element that can dynamically expand to show all content. With that being the case, I don't want to strip HTML tags and then show them only when full expanded. HTML should remain as is in the collapsed and expanded states.

推荐答案

如果这是为了在页面上显示,可以采用更简洁的方式是使用CSS。鉴于HTML:

If this is for display on a page, a neater way may be to use CSS. Given the HTML:

    <span class="truncated">this is truncated text</span>

和CSS:

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

这将显示类似于:

    this is...

你然后可以使用JavaScript在需要时删除CSS类。示例实施: http://jsfiddle.net/a8QK4/

You can then use JavaScript to remove the CSS class when required. Sample implementation: http://jsfiddle.net/a8QK4/

这篇关于截断可能包含或不包含HTML元素的段落文本的最快捷方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆