从 contentEditable div 中删除格式

我有一个 contentEditable Div,我想删除任何格式,尤其是复制和粘贴文本.

I have a contentEditable Div and I want remove any formatting especially for copy and paste text.

推荐答案

你试过使用innerText吗?

Have you tried using innerText?

添加:

如果您想从粘贴到可编辑 div 的内容中去除标记,请尝试创建临时 div 的旧技巧 - 请参见下面的示例.

If you want to strip markup from content pasted into the editable div, try the old hack of creating a temporary div -- see example below.

<!DOCTYPE html>
<html>

<head> 
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>Strip editable div markup</title>

  <script type="text/javascript">
    function strip(html) {
      var tempDiv = document.createElement("DIV");
      tempDiv.innerHTML = html;
      return tempDiv.innerText;
    }
  </script>
</head>

<body>
  <div id="editableDiv" contentEditable="true"></div>
  <input type="button" value="press" onclick="alert(strip(document.getElementById('editableDiv').innerText));" />
</body>

</html>

相关文章