您可以实现类似这样的事情,而不需要textarea
处理内容中的代码时,每当其值发生更改时都可编辑div
,并删除除段落和换行符之外的所有标签。
的想法将是每一个div中内容的变化(听input
事件)时间:
- 在内HTML替换所有
</p>
和<br>
非HTML标记(如:[p]
和[br]
)。
- 删除所有的HTML标签(你可以用
.text()
做)
- 装回用于其等效令牌(和它们的开口!)
- 裹一切
<p>
和</p>
之间。
这里一个简单的演示:
$("#editable").on("input", function() {
$this = $(this);
// replace all br and closing p tags with special tokens
$this.html($this.html().replace(/\<\/p\>/g,"[p]").replace(/\<br\>/g,"[br]"));
// remove all the tags, and then replace the tokens for their original values
$this.html("<p>" + $this.text().replace(/\[p\]/g, "</p><p>").replace(/\[br\]/g,"<br>") + "</p>");
});
div#editable, div#demo {
border:1px solid gray;
padding:6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div contenteditable="true" id="editable"></div>
<h3>Demo</h3>
<p>Copy this code and paste it on the editable div above:</p>
<div id="demo">
<p>This <b>is</b> <i>a</i> styled paragraph.</p>
<p> </p>
<p>The <span style="font-weight:bold">above paragraph</span> is empty.</p>
<p>And this is a new paragraph…<br>with a line break!</p>
</div>
你也可以看到它运行在这样的jsfiddle:http://jsfiddle.net/v5rae96w/
我试着用MS Word和HTML,它这个解决方案工作正常。但它有一个问题:它只与p
和br
(与MS Word和其他文字处理器很好地配合)进行换行。如果用户复制HTML如div
(或其他导致换行符的块元素),则它不会很好地工作。如果您需要与所有块元素断开连接,则此解决方案可能需要进行一些更改。
为了解决这个问题,你可以用p
(或div
或你想要的元素)替换所有的块标记,通过指示它的正则表达式:
$this.html().replace(/(\<\/p\>|\<\/h1\>|\<\/h2\>|\<\/div\>)/gi,"[p]")
正如你所看到的在这里:
$("#editable").on("input", function() {
$this = $(this);
// replace all closing block tags with special token
$this.html($this.html().replace(/(\<\/p\>|\<\/h1\>|\<\/h2\>|\<\/h3\>|\<\/h4\>|\<\/h5\>|\<\/h6\>|\<\/div\>)/gi,"[p]").replace(/\<br\>/gi,"[br]"));
// remove all the tags
$this.html("<p>" + $this.text().replace(/\[p\]/g,"</div><p>").replace(/\[br\]/g,"<br>") + "</p>");
});
div#editable, div#demo {
border:1px solid gray;
padding:6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div contenteditable="true" id="editable"></div>
<div>
<h3>Demo</h3>
<p>Copy this code and paste it on the editable div above:</p>
<div id="demo">
<p>This <b>is</b> <i>a</i> styled paragraph.</p>
<p> </p>
<p>The <span style="font-weight:bold">above paragraph</span> is empty.</p>
<p>And this is a new paragraph…<br>with a line break!</p>
</div>
</div>
或者在这JSFiddle:http://jsfiddle.net/v5rae96w/1/
因为客户端将粘贴文本从微软word,和其他编辑 – djt
有点困惑,为什么这是倒票。我解释了我想要做什么,我尝试了什么,为什么它不起作用。 – djt