通過 JavaScript 擷取和設定游標在輸入框中的位置(相容 IE 及 Firefox)

來源:互聯網
上載者:User

function getLocation(elm) { 
    if(elm.createTextRange) { // IE              
        var range = document.selection.createRange();                
        range.setEndPoint('StartToStart', elm.createTextRange());                
        return range.text.length; 
    } else if(typeof elm.selectionStart == 'number') { // Firefox 
        return elm.selectionStart; 
    } 

 
function setLocation(elm, n) { 
    if(n > elm.value.length) 
        n = elm.value.length; 
    if(elm.createTextRange) {   // IE 
        var textRange = elm.createTextRange(); 
        textRange.moveStart('character', n);             
        textRange.collapse();        
        textRange.select();      
    } else if(elm.setSelectionRange) { // Firefox 
        elm.setSelectionRange(n, n); 
        elm.focus(); 
    } 


其中幾個函數的說明:

IE:

  TextRange.setEndPoint('StartToStart', elm.createTextRange()):將 TextRange 的起始位置調整到 elm.createTextRange() 的起始位置處。第二個參數必須是一個 TextRange,第一個參數必須為以下四個值:StartToStart、StartToEnd、EndToStart、EndToEnd,StartToStart 的意思就是將 TextRange 的起始位置設定為第二個參數的起始位置,同理可知 StartToEnd 的意思就是將 TextRange 的起始位置設定為第二個參數的終止位置,依此類推,EndToStart 和 EndToEnd 也就很好理解了。
  TextRange.moveStart('character', n): 將 TextRange 的起始位置後移到 n 個字元處,另外還有一個函數是 moveEnd('character', n),這是移動 TextRange 的終止位置,若要將終止位置前移,應使用 -n 而不是 n(假定 n 為正數)。

  TextRange.collapse():將文本插入點設定到 TextRange 當前起始位置處,若要設定到終止位置處,使用 TextRange.collapse(false)。實際上,設定插入點就是起點和終點設定到同一位置上,這大概也就是 collapse 這個名稱的來由吧。所以,該語句也可換成 textRange.moveEnd('character', n - elm.value.length),只是看起來沒那麼簡明而已。

  關於 TextRange 對象,查詢一下 IE 的 DOM 手冊便知。

 

Firefox:

  Firefox 下就簡單得多了,Element.setSelectionRange(start, end):選取 Element 的文本中從起始位置 start 到終止位置 end 處的文本,同上,要設定插入點,將起始位置和終止位置設為同一個就可以了。


摘自 orain的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.