【问题标题】:How to change contenteditable input character, on keypress如何在按键上更改内容可编辑的输入字符
【发布时间】:2016-09-14 08:10:44
【问题描述】:

我有一个内容可编辑的 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>

为什么这不起作用?

【问题讨论】:

    标签: jquery keypress contenteditable


    【解决方案1】:

    要在 contenteditable 中添加字符,您必须获取光标位置并粘贴到同一位置。

    你可以试试下面的代码。 此代码由@Tim_Down 在此处提出:Changing the keypressNeed 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;
        }
    }
    <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>

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多