2012-01-19 33 views
3

我發現這對一個不同的問題:setSelectionRange在瀏覽器中的行爲方式不同?

setCaretToPos = function(input, selectionStart, selectionEnd){ 
     if(input.setSelectionRange){ 
     input.focus(); 
     input.setSelectionRange(selectionStart, selectionEnd); 

     }else if(input.createTextRange){ 
     var range = input.createTextRange(); 
     range.collapse(true); 
     range.moveEnd('character', selectionEnd); 
     range.moveStart('character', selectionStart); 
     range.select(); 
     } 
    }; 

setCaretToPos(8, 12); 

應該從8字符和12字符之間的文本區域中選擇文本。

它適用於Firefox和Chrome,但在Opera中,我得到了錯誤的選擇。偏移移動兩個字符後面

它有什麼問題?


看來它與新行有關: \n,因爲如果文本不包含新行字符,則選擇是正確的。

+0

我看到它是你缺少你的函數的輸入參數的方式。它在參數列表中,但你沒有將它傳遞給你的函數。檢查了這一點:http://jsfiddle.net/7Tsx6/並嘗試刪除document.getElementById部分,並嘗試這兩種情況。 –

+0

不,這只是我的問題中的一個錯誤,忘記添加輸入參數。問題出現在textarea有新行 – Alex

+1

基於上面的評論你是傳遞jQuery對象還是實際的元素? – Seth

回答

6

新行是Opera和IE中textareas中的兩個字符(CRLF或\r\n),以及其他瀏覽器中的一個字符(\n)。你需要爲此進行調整。這是一個功能,可以將換行符作爲所有瀏覽器中的單個字符處理。

現場演示:http://jsfiddle.net/DqtVK/1/

代碼:

function adjustOffset(el, offset) { 
    var val = el.value, newOffset = offset; 
    if (val.indexOf("\r\n") > -1) { 
     var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g); 
     newOffset += matches ? matches.length : 0; 
    } 
    return newOffset; 
} 

var setCaretToPos = function(input, selectionStart, selectionEnd){ 
    input.focus(); 
    if(input.setSelectionRange){ 
    selectionStart = adjustOffset(input, selectionStart); 
    selectionEnd = adjustOffset(input, selectionEnd); 
    input.setSelectionRange(selectionStart, selectionEnd); 

    }else if(input.createTextRange){ 
    var range = input.createTextRange(); 
    range.collapse(true); 
    range.moveEnd('character', selectionEnd); 
    range.moveStart('character', selectionStart); 
    range.select(); 
    } 
}; 
+0

謝謝,完美作品:D – Alex

相關問題