How to change contenteditable input character, on

2019-06-13 08:13发布

问题:

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>

Why this not work?

回答1:

For add a character in contenteditable, you must get cursor position and paste at same position.

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>