0

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.

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

Code:

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 :)

4

1 回答 1

0

jQuery.text方法只返回纯文本。尝试.html改用。
例子:

var text = currentCol.html();

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

var wordArray=text.split(' ');

您可能想将其更改为

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

这是一种解决方法,因为您可以遍历每个正则表达式匹配并在每个空格字符上对其进行子串化,但恕我直言,上述%^%组合的想法要简单得多。你可以用你想要的任何东西替换这三个标志。我只是认为它足够独特,不会用于任何其他目的。
上面的正则表达式是简化的,并假设您没有在文本中使用<>签名。
如果你真的这样做,我建议用&lt;and替换它们&gt;

于 2013-10-10T08:42:34.193 回答