检测按键上的字符

Detecting characters on keypress

假设在文本输入字段中,我正在输入一个句子。然后我输入某个字符,例如“@”,如下所示:

I am writing this example with @ symbol.

使用keypress,当符号被使用时,我想检查它前后的字符。

在这种情况下,它会给出两个空的spaces。

另一个例子是:

This is another example using @text.

这里应该给 space 作为 "before" 和 "t" 作为 "after" 符号。

当按键条件满足时,我如何检测这些字符?

任何建议将不胜感激。

在您的输入元素上将 input eventselectionStart 属性 结合使用,这样您就可以获取光标的位置。

document.getElementById('example').addEventListener('input', function () {
    var text = this.value,
        cursor = this.selectionStart
    
    // the characters in question
    var previous = text.charAt(cursor - 2),
        current  = text.charAt(cursor - 1),
        next     = text.charAt(cursor)
    
    // do something cool
    console.log(previous, '|', current, '|', next)
})
<input type="text" id="example" value="edit this example text :)"/>