我有一个div,其contentEditable =“true”,需要为输入的数字着色

这是我的代码,适用于着色可编辑div中的数字,但光标将转到div的开头,当我按下键盘箭头按钮来遍历字符串时,它应该正常工作,当我点击“home”和“结束“按钮,光标应按预期方式进行

jQuery(document).ready(function(){ $("#richTextField").keyup(function() { var divContent = $(this).text(); var pattern = /(\d)/g; var replaceWith = '$1'; var highlighted = divContent.replace(pattern,replaceWith); $(this).html(highlighted); }); }); 

elimate你不想运行该函数的键,这样的东西(即应该正常运行)

 $("#richTextField").keyup(function(e) { var excludeKeyCodes = [8, 9, 13, 46, 35 ,36 ,37, 38, 39, 40]; if( !$.inArray(e.which, excludeKeyCodes )) { var divContent = $(this).text(); var pattern = /(\d)/g; var replaceWith = '$1'; var highlighted = divContent.replace(pattern,replaceWith); $(this).html(highlighted); } }); 

供参考javascript密钥代码

快速摘要

8 – Backspace,9 – Tab,13 – Enter,46 – 删除,35 – 结束,36 – home,37,38,39,40 – 箭头(左,上,右,下)

以下是您想要的:

 jQuery(document).ready(function () { $("#richTextField").keyup(function () { var divContent = $(this).text().split(''); var pattern = /(\d)/; var replaceWith = '$1'; var highlighted = divContent.map(function (u) { if (pattern.test(u)) return $(u.replace(pattern, replaceWith)); else return document.createTextNode(u); }); var caretPos = getCaretCharacterOffsetWithin(this); $(this).empty().append(highlighted); setCursor(this, caretPos); }); }); function getCaretCharacterOffsetWithin(element) { var caretOffset = 0; if (typeof window.getSelection != "undefined") { var range = window.getSelection().getRangeAt(0); var preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.endContainer, range.endOffset); caretOffset = preCaretRange.toString().length; } else if (typeof document.selection != "undefined" && document.selection.type != "Control") { var textRange = document.selection.createRange(); var preCaretTextRange = document.body.createTextRange(); preCaretTextRange.moveToElementText(element); preCaretTextRange.setEndPoint("EndToEnd", textRange); caretOffset = preCaretTextRange.text.length; } return caretOffset; } function setCursor(node, pos) { if (!node) { return false; } else if (document.createRange) { range = document.createRange(); range.selectNodeContents(node); range.setStart(node, pos); range.setEnd(node, pos); selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } else if (node.createTextRange) { var textRange = node.createTextRange(); textRange.collapse(true); textRange.moveEnd(pos); textRange.moveStart(pos); textRange.select(); return true; } else if (node.setSelectionRange) { node.setSelectionRange(pos, pos); return true; } return false; } 

这个JS Fiddle提供了一个工作演示: http : //jsfiddle.net/B3PgU/


代码片段取自:

https://stackoverflow.com/a/4812022/1662998

https://stackoverflow.com/a/2920149/1662998