如何在按键时更改可编辑内容的输入字符 [英] How to change contenteditable input character, on keypress
本文介绍了如何在按键时更改可编辑内容的输入字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个内容可编辑的div,我想在按键事件触发时修改输入字符:
I have a content editable div and I want to modify input character when key press event fired:
$('#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>
为什么这不起作用?
推荐答案
要在contenteditable中添加字符,必须获得光标位置并将其粘贴在同一位置.
For add a character in contenteditable, you must get cursor position and paste at same position.
您可以尝试下面的代码. 该代码由@Tim_Down在此处提出:更改按键和
You can try the code below. This code propose by @Tim_Down here: Changing the keypress and Need to set cursor position to the end of a contentEditable div, issue with selection and range objects
通过此操作,您可以制作一个地图键,以在触发键时添加您想要的每个事件.
with this you can make a map keys for add each event you want on key fired.
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;
}
}
<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>
这篇关于如何在按键时更改可编辑内容的输入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文