我正在尝试创建一个 HTML5 contenteditable div,它只接受纯文本。我在下面使用 html 和 jQuery:
HTML
<div contenteditable="true"></div>
jQuery
(function () {
$('[contenteditable]').on('paste', function (e) {
e.preventDefault();
var text = null;
text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Paste Your Text Here');
document.execCommand("insertText", false, text);
});
});
但它并不适用于所有浏览器。 getData
在 Internet Explorer 浏览器中不支持。我在 stackoverflow 上尝试了很多解决方案,但没有一个对我有用。
我也试过
(function () {
$('[contenteditable]').on('paste', function (e) {
e.preventDefault();
var text = null;
if (window.clipboardData && clipboardData.setData) {
text = window.clipboardData.getData('text');
} else {
text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Paste Your Text Here');
}
document.execCommand("insertText", false, text);
});
});
但在那种情况下 document.execCommand("insertText", false, text);
不适用于 IE。
是否有任何方法可以在过滤 HTML 标记后接受数据,以便任何人都可以通过类型、粘贴、拖放或任何其他方式在可编辑的 div 中输入数据。它应该将其显示为文本。
最佳答案
试试这个:
<div contenteditable="plaintext-only"></div>
引用:https://w3c.github.io/editing/contentEditable.html#h-contenteditable
关于javascript - HTML5 contenteditable div 只接受明文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24408028/