将新行更改为<p>包裹在iFrame中

Change new line to <p> wrap in iFrame?

本文关键字:包裹 iFrame gt 新行更 lt      更新时间:2023-09-26

当我在IE11中将文本粘贴到iFrame中时,它会忽略/n,而是将其变成空白。由于我想保持粘贴文本的格式,我希望保留新行。

由于IE会自动将新行处理为新段落,所以在粘贴文本时,我更喜欢保持这种方式。这是我的代码

//Html is the text obtained from the clipboard. New lines are stored as /n
html = html.replace(/'n'n/g, '</p><p><br>');
html = html.replace(/'n/g, '</p><p>');
html = '<p>'+html+'</p>'

这在大多数情况下都很好,尽管浏览器出于某些原因在粘贴文本的开头添加了一个额外的p标记(但没有结束标记)

这导致了相当多令人讨厌的错误。有更好的方法吗?

您可以执行拆分/联接方法,看看这个例子。对于以下html:

<textarea class="pasted_text">Line 1
Line 2
Line 3
Line 5
</textarea>
<h4>Result (paragraphs have blue border):</h4>
<div class="result_text"></div>

我们使用'n分割字符串,clean和than使用段落标签连接:

var pastedText = $('.pasted_text').val();
/* Split text on new lines */
var split = pastedText.split(''n');
/* Remove empty paragraphs */
var clean = split.filter(function(n){ return n });
/* Join back with paragraph tags */
var joined = clean.join('</p><p>');
/* Enclose with paragraph */
var result = '<p>'+joined+'</p>';
/* Print output */
$('.result_text').html( result );

我认为用div替换p应该可以修复它。p标记很棘手。