contenteditable 光標定位到最後

在Vue作項目時,作了一個div[contenteditable=true]的組件做爲文本輸入框vue

在非手動輸入值後,光標會丟失,經測試如下這段代碼可用,直接將光標定位到最後異步

function keepLastIndex(obj) {
        console.log(obj)
        console.log(window.getSelection)
        console.log(document.selection)
        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();
        }
    }
---------------------

在實際使用時,vue.$emit是一個異步函數,最好在調用這個定位前加上必定的延遲,經測試,5ms就能夠了函數

setTimeout(()=>{
    keepLastIndex(e.target)
},5)

原文:http://www.javashuo.com/article/p-uvhgwkun-go.html測試

相關文章
相關標籤/搜索