How to track caret/cursor in contenteditable?

后端 未结 4 870
栀梦
栀梦 2021-02-07 04:40

I\'d like to track the movement of the caret/cursor in a contenteditable. I\'m not sure what\'s the best way to do this, though.

I\'m currently listening for click, key

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 05:21

    WRT catching the event after the selection is updated: I simply wrap my handler functions in timeouts:

    editor.onkeydown = function() {
      window.setTimeout( function(){
        // Your handler code here
      }, 0 );
    };
    

    This registers your handler to be executed in the browser's event loop as soon as possible, but after the current (eg click) event is processed. But be aware of possible races if you have other scripts modifying the content; there is no guarantee that your timeout is the next in line to be run.

提交回复
热议问题