我有一个 contentEditable 字段,我想在其中执行以下操作。当用户将富文本粘贴到字段(Microsoft Word 或其他)时,我想去除所有富文本,但保留换行符。
我的想法是:如果将富文本粘贴到普通 <texarea>
中,它会删除所有格式并保留中断(由显式换行以及 block 级元素创建)。我想以某种方式模拟这个。换句话说,创建一个临时文本区域,拦截粘贴事件,将其应用到文本区域,检索结果,并将它们插入回原始内容可编辑字段。
但是,我还没有找到模拟这个的方法。如果我通过 jquery 将内容粘贴到 textarea 中,当我尝试从那里复制它时似乎会重新设置所有富文本格式,回到原始字段
最佳答案
你可以在不需要 textarea
的情况下实现这样的目标, 只是处理内容中的代码 editable 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
(或其他导致换行的 block 元素),它不会很好地工作。如果您需要打破所有 block 元素,此解决方案可能需要进行一些更改。
要解决这个问题,您可以将所有 block 标记替换为 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/
关于javascript - JQuery - 粘贴事件,剥离富文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629153/