2011-10-02 64 views

回答

3

在所有現代瀏覽器:

//input refers to the text box 
if(input.value.length == input.selectionEnd){ 
    //Caret at end. 
} 

輸入元素的selectionEnd屬性等於最高的選擇指數。

+1

'selectionEnd'總是比'selectionStart'大;你可以放心地使用'selectionEnd'。 – pimvdb

+1

@pimvdb:那麼'selectionEnd'總是和'selectionStart'一樣大。 –

+0

@Tim Down:是的,你是對的。但是,如果它們相等,使用'selectionEnd'仍然是安全的。 – pimvdb

2
<script> 
input = document.getElementById('yourinputfieldsid'); 
if(input.selectionEnd == input.selectionStart && input.value.length == input.selectionEnd){ 
//your stuff 
} 
</script> 

這將檢查插入符號是否在最後,並確保它不僅僅是因爲選擇它顯示結束值。

2

當你選擇了一些文本時,你不會指定你想要發生什麼,所以在這種情況下,我的代碼只是檢查選擇的末尾是否在輸入的末尾。 (其他答案不會:IE只在版本9中獲得selectionStartselectionEnd)。這是一個跨瀏覽器的功能,可以在IE瀏覽器中工作()(其他答案不會:IE只在版本9中獲得selectionStartselectionEnd)。

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

代碼:

function isCaretAtTheEnd(el) { 
    var valueLength = el.value.length; 
    if (typeof el.selectionEnd == "number") { 
     // Modern browsers 
     return el.selectionEnd == valueLength; 
    } else if (document.selection) { 
     // IE < 9 
     var selRange = document.selection.createRange(); 
     if (selRange && selRange.parentElement() == el) { 
      // Create a working TextRange that lives only in the input 
      var range = el.createTextRange(); 
      range.moveToBookmark(selRange.getBookmark()); 
      return range.moveEnd("character", valueLength) == 0; 
     } 
    } 
    return false; 
}