Tar*_*run 8 html javascript jquery html5
我正在尝试创建一个HTML5 contenteditable div,它只接受纯文本.我在下面使用html和jQuery:
HTML
<div contenteditable="true"></div>
Run Code Online (Sandbox Code Playgroud)
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);
});
});
Run Code Online (Sandbox Code Playgroud)
但它并不适用于所有浏览器.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);
});
});
Run Code Online (Sandbox Code Playgroud)
但在那种情况下document.execCommand("insertText", false, text);,IE不起作用.
是否有任何方法可以在过滤HTML标记后接受数据,因此任何人都可以通过类型,粘贴,删除或任何其他方式在可编辑的div中输入数据.它应该显示为文本.
不是jQuery的忠实粉丝,我的解决方案不会使用它.无论如何它在这里(它应该工作,作为纯javascript):
function convertToPlaintext() {
var textContent = this.textContent;
this.innerHTML = "";
this.textContent = textContent;
}
var contentEditableNodes = document.querySelectorAll('[contenteditable]');
[].forEach.call(contentEditableNodes, function(div) {
div.addEventListener("input", convertToPlaintext, false);
});Run Code Online (Sandbox Code Playgroud)
小智 7
尝试这个:
<div contenteditable="plaintext-only"></div>
Run Code Online (Sandbox Code Playgroud)
参考:https : //w3c.github.io/editing/contentEditable.html#h-contenteditable
| 归档时间: |
|
| 查看次数: |
6085 次 |
| 最近记录: |