Vue中div contenteditable 的光標定位


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

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

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)

//或者

this.$nextTick(()=>{
  keepLastIndex(e.target)
})
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM