Set cursor position on contentEditable

后端 未结 8 2048
悲&欢浪女
悲&欢浪女 2020-11-22 09:05

I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable=\'on\'

regains focus. It appears
8条回答
  •  醉酒成梦
    2020-11-22 09:30

    I took Nico Burns's answer and made it using jQuery:

    • Generic: For every div contentEditable="true"
    • Shorter

    You'll need jQuery 1.6 or higher:

    savedRanges = new Object();
    $('div[contenteditable="true"]').focus(function(){
        var s = window.getSelection();
        var t = $('div[contenteditable="true"]').index(this);
        if (typeof(savedRanges[t]) === "undefined"){
            savedRanges[t]= new Range();
        } else if(s.rangeCount > 0) {
            s.removeAllRanges();
            s.addRange(savedRanges[t]);
        }
    }).bind("mouseup keyup",function(){
        var t = $('div[contenteditable="true"]').index(this);
        savedRanges[t] = window.getSelection().getRangeAt(0);
    }).on("mousedown click",function(e){
        if(!$(this).is(":focus")){
            e.stopPropagation();
            e.preventDefault();
            $(this).focus();
        }
    });
    

    savedRanges = new Object();
    $('div[contenteditable="true"]').focus(function(){
        var s = window.getSelection();
        var t = $('div[contenteditable="true"]').index(this);
        if (typeof(savedRanges[t]) === "undefined"){
            savedRanges[t]= new Range();
        } else if(s.rangeCount > 0) {
            s.removeAllRanges();
            s.addRange(savedRanges[t]);
        }
    }).bind("mouseup keyup",function(){
        var t = $('div[contenteditable="true"]').index(this);
        savedRanges[t] = window.getSelection().getRangeAt(0);
    }).on("mousedown click",function(e){
        if(!$(this).is(":focus")){
            e.stopPropagation();
            e.preventDefault();
            $(this).focus();
        }
    });
    div[contenteditable] {
        padding: 1em;
        font-family: Arial;
        outline: 1px solid rgba(0,0,0,0.5);
    }
    
    

提交回复
热议问题