我有一个contentEditable字段,我想在其中执行以下操作。当用户将富文本粘贴到字段(microsoft或其他字段)时,我想删除所有的富文本,但保留换行。
我的想法是:如果将丰富的文本粘贴到普通的<texarea>
中,它会删除所有格式并保留断点(由显式新行以及块级元素创建)。我想以某种方式来模拟这个。换句话说,创建一个临时文本区域,拦截粘贴事件,将其应用到textarea,检索结果,并将它们插入原始内容可编辑字段。
然而,我还没有找到一种方法来模拟这个过程。如果我通过jquery将内容粘贴到文本区域中,那么当我尝试将内容复制到原来的字段时,它似乎会重新运行所有的富文本格式。
发布于 2015-06-03 20:39:38
您可以在不需要textarea
的情况下实现这样的目标,只要每次更改内容可编辑div
中的代码,并删除除段落和换行之外的所有标记。
这样做的想法是,每当div中的内容发生变化时(侦听input
事件):
</p>
和<br>
替换非HTML标记(例如:[p]
和[br]
)。.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和HTML尝试了这个解决方案,它工作得很好。但它有一个问题:它只对p
和br
(与MS和其他字处理器很好地工作)进行换行操作。如果用户复制div
之类的HTML (或其他导致中断行的块元素),它将不能很好地工作。如果您需要使用所有块元素,则此解决方案可能需要进行一些更改。
要解决这个问题,可以将所有块标记替换为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/上
https://stackoverflow.com/questions/30629153
复制相似问题