Javascript 确定插入符号何时到达输入框的末尾

Javascript 确定插入符号何时到达输入框的末尾,javascript,Javascript,我找到了一个解决方案,可以计算插入符号在文本或输入框中的确切位置 就我而言,这太过分了。我只想知道插入符号何时位于输入框所有文本的末尾。有没有一种简单的方法可以做到这一点?在所有现代浏览器中: //input refers to the text box if(input.value.length == input.selectionEnd){ //Caret at end. } 输入元素的selectionEnd属性等于最高的选择索引。 <script> input =

我找到了一个解决方案,可以计算插入符号在文本或输入框中的确切位置


就我而言,这太过分了。我只想知道插入符号何时位于输入框所有文本的末尾。有没有一种简单的方法可以做到这一点?

在所有现代浏览器中:

//input refers to the text box
if(input.value.length == input.selectionEnd){
    //Caret at end.
}
输入元素的
selectionEnd
属性等于最高的选择索引。


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

这将检查插入符号是否实际位于末尾,并确保它不仅因为选择而显示一个结束值。

在选择某些文本时,您没有指定要执行的操作,因此在这种情况下,我的代码只检查选择的结尾是否位于输入的末尾

这里有一个在IE<9中可以使用的跨浏览器功能(其他答案不会:IE只在9版中获得
selectionStart
selectionEnd

现场演示:

代码:

函数为循环结束(el){
var valueLength=el.value.length;
如果(el.selectionEnd的类型==“编号”){
//现代浏览器
返回el.selectionEnd==valueLength;
}else if(文档选择){
//IE<9
var selRange=document.selection.createRange();
if(selRange&&selRange.parentElement()==el){
//创建仅存在于输入中的工作TextRange
var range=el.createTextRange();
range.moveToBookmark(selRange.getBookmark());
返回范围.moveEnd(“字符”,valueLength)==0;
}
}
返回false;
}

selectionEnd
始终大于
selectionStart
;您可以安全地使用
selectionEnd
@pimvdb:嗯,
selectionEnd
总是至少与
selectionStart
一样大。@Tim Down:是的,您是对的。但是,如果它们相等,使用
selectionEnd
仍然是安全的。
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;
}