How to track caret/cursor in contenteditable?

后端 未结 4 864
栀梦
栀梦 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:10

    In Mozilla and Opera, the nasty business of handling key and mouse events is your only option. Not only is it fiddly, it also doesn't cover every case: it's possible to change the selection via the edit and context menus (via Select All, for example). To cover that, you'd also need to add some kind of polling of the selection object.

    However, in IE (all the way back to at least 5.5) and recent-ish WebKit, there is a selectionchange event that fires on the document whenever the selection changes.

    document.onselectionchange = function() {
        alert("Selection changed!");
    };
    

    There is a chance that Mozilla will support it in the future: https://bugzilla.mozilla.org/show_bug.cgi?id=571294

提交回复
热议问题