How to track caret/cursor in contenteditable?

后端 未结 4 961
栀梦
栀梦 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

    It's not an easy task for the reasons you said. I came up with some kludge like this:

    var caretInterval, caretOffset;
    document.addEventListener("keydown", function(e) {
        if (!e.target.contentEditable || caretInterval) return;
        if (e.keyCode !== 37 && e.keyCode !== 39) // Left and right
            return;
        var sel = getSelection();
        caretInterval = setInterval(function() {
            if (sel.type === "Caret") caretOffset = sel.baseOffset;
        }, 50);
    });
    document.addEventListener("keyup", function(e) {
        if (e.keyCode !== 37 && e.keyCode !== 39) // Left and right
            return;
        clearInterval(caretInterval);
        caretInverval = null;
        var sel = getSelection();
        if (sel.type === "Caret") caretOffset = sel.baseOffset;
    });
    

    There could be a small problem if someone tries to press left and right at the same time. For ctrl-X and ctrl-V, you should catch the cut and paste event, and that's actually another pain in the bollocks.

    In the end, I decided it wasn't worth the effort for my purposes. Maybe you have different needs.

提交回复
热议问题