JS solves the cursor position of contenteditable="true" and puts it at the end

JS solves the cursor position of contenteditable="true" and puts it at the end.
After the element is set to be editable, there is a problem with the position of the cursor when inputting. I searched online and it worked, and recorded it. I advise everyone to try to use the input tag to edit the experience better, and save some problems

function keepLastIndex(obj) {
    
    
    if (window.getSelection) {
    
    //ie11 10 9 ff safari
        obj.focus(); //解决ff不获取焦点无法定位问题
        var range = window.getSelection();//创建range
        range.selectAllChildren(obj);//range 选择obj下所有子内容
        range.collapseToEnd();//光标移至最后
    }
    else if (document.selection) {
    
    //ie10 9 8 7 6 5
        var range = document.selection.createRange();//创建选择对象
        //var range = document.body.createTextRange();
        range.moveToElementText(obj);//range定位到obj
        range.collapse(false);//光标移至最后
        range.select();
    }
}
keepLastIndex(document.getElementById("div"))

Guess you like

Origin blog.csdn.net/weixin_44461275/article/details/126282272