另一个div中的html文本溢出 [英] Overflowed text with html in another div

查看:217
本文介绍了另一个div中的html文本溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让文本在另一个div中溢出,因此我找到并使用了此答案,来自另一个问题,网址为Stackoverflow.

I want to have a text that overflows in another div, so I found and used this answer from another question at Stackoverflow.

问题是仅显示纯文本;链接,粗体/斜体和段落将被忽略.

The problem is that only plain text is displayed; links, bold/italics and paragraphs are ignored.

这是答案中的相同的jsfiddle ,但带有html标记.我如何显示它们?

Here is the same jsfiddle from the answer, but with added html tags. How do i get to display them?

代码:

var currentCol = $('.col:first');
var text = currentCol.text();
currentCol.text('');
var wordArray=text.split(' ');

$.fn.hasOverflow = function() {
   var div= document.getElementById( $(this).attr('id') ); 
   return div.scrollHeight>div.clientHeight;
};

for ( var x = 0; x < wordArray.length; x++ ) {
    var word = wordArray[x];
    currentCol.append(word+' ');
    if ( currentCol.hasOverflow() ) {
        currentCol = currentCol.next('.col');
    }
}

任何提示或建议将不胜感激:)

Any tips or advice will be appreciated :)

推荐答案

jQuery .text方法仅返回纯文本.尝试改用.html.
示例:

jQuery .text method returns only plain text. Try using .html instead.
Example:

var text = currentCol.html();

但是,如果您的标签包含任何空格(例如<span class="some-class">),则代码中的以下行将使您的文本混乱

But if your tags contain any spaces (like <span class="some-class">) then the following line from your code will do a mess with your text

var wordArray=text.split(' ');

您可能希望将其更改为

text = text.replace(/ (?![^<>]*>)/gi, '%^%');
var wordArray = text.split('%^%');

这是一种变通方法,因为您可以遍历每个正则表达式匹配项,并在每个空格字符上对其进行子串处理,但是恕我直言,使用%^%组合的上述想法要简单得多.您可以将3个标志替换为所需的任何符号.我只是认为它足够独特,不会用于任何其他目的.
上面的正则表达式经过简化,并假定您在文本中未使用<>标记.
如果确实需要,我建议还是将它们替换为&lt;&gt;.

This is kind of workaround since you could iterate over each regex match and substring it on every space character but IMHO the above idea with %^% combination is much more simple. you can replace those 3 signs with anything you want. I just thought it is unique enough that won't be used in any other purpose.
Above regular expression is simplified and assumes that you don't use < and > signs in your text.
If you actually do I would recommend to replace them with &lt; and &gt; anyway.

这篇关于另一个div中的html文本溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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