JavaScript DOM contenteditable auto focus

使用div模拟textarea时候,div的focus方法容易导致光标错乱,该方法利用getSelection来实现和input的focus方法相同的效果。

const autoFocus = el => {
    if (window.getSelection) { //ie11 10 9 ff safari
        // 解决ff不获取焦点无法定位问题
        el.focus() 
        const range = window.getSelection() //创建range
        range.selectAllChildren(el) // range 选择el下所有子内容
        range.collapseToEnd() // 光标移至最后
    } else if (document.selection) { // ie10 9 8 7 6 5
        const range = document.selection.createRange() // 创建选择对象
        //const range = document.body.createTextRange()
        range.moveToElementText(el) // range定位到el
        range.collapse(false) // 光标移至最后
        range.select()
    }
}
为之则易,不为则难。
原文地址:https://www.cnblogs.com/coderDemo/p/14580460.html