简体   繁体   English

如何在contenteditable中的插入符号处输入字符?

[英]How to input characters at the caret in a contenteditable?

How do I input a character, with either JQuery or plain JavaScript, as if it had been typed? 如何使用JQuery或纯JavaScript输入字符,就像输入了字符一样?

I have a contenteditable section, and am intercepting user input in order to replace certain characters (for example straight quotes with curly ones). 我有一个contenteditable部分,并且正在拦截用户输入以便替换某些字符(例如,用大括号括起来的直引号)。 I have the following JQuery to intercept a character, but am not sure of the best way to input the new character. 我有以下JQuery来截取字符,但不确定输入新字符的最佳方法。

$('.editor').keypress(function(e) {
    console.log(e.which);
    if (e.which === 39) {
        e.preventDefault();
        // replace with curly quotes
    }
});

What about document.execCommand: 那么document.execCommand呢:

$('.editor').keypress(function(e) {
  console.log(e.which);
  if (e.which === 39) {
    e.preventDefault();
    document.execCommand('insertHTML', false, 'String To Insert');
  }
});

insertHTML doesn't work in IE so use: insertHTML在IE中不起作用,因此请使用:

document.selection.createRange().pasteHTML('html to insert');

A list of commands and examples can be found at: https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla 可以在以下位置找到命令和示例列表: https : //developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla


PS I think e.which will report 0 in certain browsers so do something like: PS我认为e。在某些浏览器中将报告0,因此请执行以下操作:

var code = e.keyCode || e.which;

You can do 你可以做

$('.editor').keypress(function(e) {
    console.log(e.which);
    if (e.which === 39) {
        e.preventDefault();
        $(this).text(function(index, text){
            return text.replace(/"/gi, '-'); // <--Change this to replace the " with what you need.
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM