JQuery - 粘贴事件,剥离富文本

时间:2015-06-03 19:38:45

标签: javascript jquery

我有一个contentEditable字段,我想要执行以下操作。当用户将富文本格式化为字段(微软词或其他)时,我想删除所有富文本,但保留换行符。

我的想法是:如果将富文本粘贴到普通<texarea>中,它会删除所有格式并保留中断(由显式新行创建,以及块级元素)。我想以某种方式模拟这个。换句话说,创建一个临时textarea,拦截粘贴事件,将其应用于Textarea,检索结果,然后将它们插回到原始的“内容可编辑”字段中。

但是,我还没有找到模拟这种方法的方法。如果我通过jquery将内容粘贴到textarea中,当我尝试从那里复制它,返回原始字段时,它似乎会恢复所有富文本格式

1 个答案:

答案 0 :(得分:2)

您可以在不需要textarea的情况下实现此类目标,只需在每次更改其值时处理内容可编辑div中的代码,并删除除段落之外的所有标记和换行。

每次内容在div中发生变化时都会想到(听input事件):

  • 在内部HTML中替换非HTML令牌的所有</p><br>(例如:[p][br]。)
  • 删除所有HTML标记(您可以使用.text()
  • 删除
  • 替换您用于等效物品的令牌(及其开口!)
  • <p></p>之间包裹所有内容。

这是一个简单的演示:

&#13;
&#13;
$("#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>");

});
&#13;
div#editable, div#demo {
    border:1px solid gray;
    padding:6px;
}
&#13;
<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>&nbsp;</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>
&#13;
&#13;
&#13;

您还可以在此JSFiddle上看到它正在运行:http://jsfiddle.net/v5rae96w/

我用MS Word和HTML尝试了这个解决方案,它运行正常。但它有一个问题:它只与pbr(与MS Word和其他文字处理器很好地协同工作)进行换行。如果用户复制像div这样的HTML(或导致换行的其他块元素),那么它就不会很好地工作。如果您需要打破所有块元素,此解决方案可能需要进行一些更改。

要解决此问题,您可以使用p(或div或您想要的元素)替换所有块标记,方法是在正则表达式上指示:

$this.html().replace(/(\<\/p\>|\<\/h1\>|\<\/h2\>|\<\/div\>)/gi,"[p]")

正如你在这里看到的那样:

&#13;
&#13;
$("#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>");

});
&#13;
div#editable, div#demo {
    border:1px solid gray;
    padding:6px;
}
&#13;
<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>
&#13;
&#13;
&#13;

或者在这个JSFiddle上:http://jsfiddle.net/v5rae96w/1/

相关问题