http://www.zhangxinxu.com/wordpress/2016/01/contenteditable-plaintext-only/ <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>如何让contenteditable元素只能输入纯文本</title> <style type="text/css"> .box { width: 500px; min-height:100px; padding: 5px; margin: 20px auto; border: 1px solid #bbb; } </style> </head> <body> <div class="box" contenteditable="true"></div> </body> <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> $('[contenteditable]').each(function() { // 干掉IE http之类地址自动加链接 try { document.execCommand("AutoUrlDetect", false, false); } catch (e) {} $(this).on('paste', function(e) { e.preventDefault(); var text = null; if(window.clipboardData && clipboardData.setData) { // IE text = window.clipboardData.getData('text'); } else { text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('在这里输入文本'); } if (document.body.createTextRange) { if (document.selection) { textRange = document.selection.createRange(); } else if (window.getSelection) { sel = window.getSelection(); var range = sel.getRangeAt(0); // 创建临时元素,使得TextRange可以移动到正确的位置 var tempEl = document.createElement("span"); tempEl.innerHTML = "&#FEFF;"; range.deleteContents(); range.insertNode(tempEl); textRange = document.body.createTextRange(); textRange.moveToElementText(tempEl); tempEl.parentNode.removeChild(tempEl); } textRange.text = text; textRange.collapse(false); textRange.select(); } else { // Chrome之类浏览器 document.execCommand("insertText", false, text); } }); // 去除Crtl+b/Ctrl+i/Ctrl+u等快捷键 $(this).on('keydown', function(e) { // e.metaKey for mac if (e.ctrlKey || e.metaKey) { switch(e.keyCode){ case 66: //ctrl+B or ctrl+b case 98: case 73: //ctrl+I or ctrl+i case 105: case 85: //ctrl+U or ctrl+u case 117: { e.preventDefault(); break; } } } }); }); </script> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » 如何让contenteditable元素只能输入纯文本 喜欢 (1)or分享 (0)