2011-10-02 65 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; 
}