停止在contenteditable div中粘贴html样式,仅粘贴纯文本 [英] Stop pasting html style in a contenteditable div only paste the plain text

查看:78
本文介绍了停止在contenteditable div中粘贴html样式,仅粘贴纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是一个contenteditable div,当我尝试粘贴某些带有样式的东西时,原本只希望复制纯文本,但是它也具有样式,有人知道如何在以下情况下强制将其转换为纯文本吗?我粘贴它,或者有人有更好的解决方案

I am using a contenteditable div, when I tried to paste something with style, it was suppose to only copy the plain text, but it got the style as well, does anyone know how to force it to convert to plain text when I paste it or anyone has a better solution

这是我的代码:

    <div contenteditable="true">   
      This text can be edited by the user. 
    </div>

推荐答案

粘贴丰富的内容时,它将显示为丰富的内容.因此,您需要捕获粘贴事件,阻止默认操作,然后从剪贴板中读取文本.

When you paste in rich content, it will be displayed as rich content. So you would need to capture the paste event, prevent the default action, and read the text from the clipboard.

var ce = document.querySelector('[contenteditable]')
ce.addEventListener('paste', function (e) {
  e.preventDefault()
  var text = e.clipboardData.getData('text/plain')
  document.execCommand('insertText', false, text)
})

  [contenteditable] {
    background-color: black;
    color: white;
    width: 400px;
    height: 200px;
  }

<div contenteditable="true"></div>

<div>
  <h1>Test content</h1>
  <p style="color:red">Copy <em>this</em> <u>underlined</u></p>
</div>

这篇关于停止在contenteditable div中粘贴html样式,仅粘贴纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆