简体   繁体   English

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

[英]Change new line to <p> wrap in iFrame?

When I paste text into my iFrame in IE11 it ignores the /n and instead turns it into whitespace. 当我将文本粘贴到IE11中的iFrame中时,它将忽略/ n并将其转换为空格。 As I would like to maintain format of pasted text, I wish to keep new lines. 由于我想保留粘贴文本的格式,因此我希望保留新行。

Since IE automatically handles new lines as new paragraphs, I would prefer to keep it that way when pasting text. 由于IE会自动将新行作为新段落处理,因此我希望在粘贴文本时保持这种方式。 Here is my code 这是我的代码

//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>'

This works fine for the most part, although the browser for some reasons adds an extra p tag at the start of the pasted text (but no closing tag) 尽管浏览器由于某些原因在粘贴的文本的开头添加了一个额外的p标签(但没有结束标签),但在大多数情况下,此方法仍然可以正常工作

This has resulted in quite a few annoying bugs. 这导致了很多烦人的错误。 Is there any better way to go about this? 有没有更好的方法来解决这个问题?

You can do split/join methods, look at this example . 您可以执行split / join方法,请看此示例 For following html: 对于以下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>

We split the string using \\n , clean and than join with paragraph tags: 我们使用\\n拆分字符串,然后使用clean进行分割,然后将其与段落标签连接:

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

I think replacing p by div should fix it. 我认为用div替换p应该可以解决它。 The p tag is tricky. p标签很棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM