How to get text cursor position after keypress event happened?

前端 未结 3 1635
悲哀的现实
悲哀的现实 2021-01-17 07:58

I am writing a syntax highlighter. The highlighter should update the highlighting immediately while entering text and navigating with the arrow keys.

The problem I\'

3条回答
  •  离开以前
    2021-01-17 08:22

    Someone just mentioned on my request for an event for caret position changes that there is also a selectionchange event, which is fired at the document everytime the selection has changed.

    This then allows to get the correct cursor position by calling window.getSelection().

    Example:

    function handleSelectionChange(evt) {
        console.log(evt.type, window.getSelection().getRangeAt(0));
    }
    
    document.addEventListener("selectionchange", handleSelectionChange);
    foo

提交回复
热议问题