jQuery Set Cursor Position in Text Area

前端 未结 16 1482
无人共我
无人共我 2020-11-21 11:42

How do you set the cursor position in a text field using jQuery? I\'ve got a text field with content, and I want the users cursor to be positioned at a certain offset when

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 12:16

    I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:

    $.fn.getCaret = function(n) {
        var d = $(this)[0];
        var s, r;
        r = document.createRange();
        r.selectNodeContents(d);
        s = window.getSelection();
        console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
        return s.anchorOffset;
    };
    
    $.fn.setCaret = function(n) {
        var d = $(this)[0];
        d.focus();
        var r = document.createRange();
        var s = window.getSelection();
        r.setStart(d.childNodes[0], n);
        r.collapse(true);
        s.removeAllRanges();
        s.addRange(r);
        console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
        return this;
    };
    

    Usage $(selector).getCaret() returns the number offset and $(selector).setCaret(num) establishes the offeset and sets focus on element.

    Also a small tip, if you run $(selector).setCaret(num) from console it will return the console.log but you won't visualize the focus since it is established at the console window.

    Bests ;D

提交回复
热议问题