我有一个内容可编辑的div,我想在按键事件触发时修改输入字符:
$('#div').on('keypress', function (e) {
e.preventDefault();
$(e.target).trigger(jQuery.Event('keypress', { which: e.which + 1728 }));
});

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div" contenteditable>
Hi I am a div
</div>
&#13;
为什么这不起作用?
答案 0 :(得分:3)
要在contenteditable中添加一个字符,您必须获得光标位置并粘贴到相同的位置。
您可以尝试以下代码。 此代码由@Tim_Down提出:Changing the keypress和Need to set cursor position to the end of a contentEditable div, issue with selection and range objects
使用此功能,您可以创建一个地图键,用于在键击时添加所需的每个事件。
var greekChars = {
"a": "\u03b1"
// Add character mappings here
};
function convertCharToGreek(charStr) {
return greekChars[charStr] || "[stack]";
}
function insertTextAtCursor(text) {
var sel, range, textNode;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
textNode = document.createTextNode(text);
range.insertNode(textNode);
// Move caret to the end of the newly inserted text node
range.setStart(textNode, textNode.length);
range.setEnd(textNode, textNode.length);
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.pasteHTML(text);
}
}
var div = document.getElementById("div");
div.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
if (charCode) {
var charStr = String.fromCharCode(charCode);
var greek = convertCharToGreek(charStr);
insertTextAtCursor(greek);
return false;
}
}
&#13;
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div" contenteditable>
Hi I am a div
</div>
&#13;