我找到this question,它提供了一個計算插入符號在文本或輸入框中的確切位置的解決方案。確定插入符號何時到達輸入框的末尾
對我而言,這是矯枉過正。我只想知道當插入符號是末尾的所有文本輸入框。有沒有簡單的方法來做到這一點?
我找到this question,它提供了一個計算插入符號在文本或輸入框中的確切位置的解決方案。確定插入符號何時到達輸入框的末尾
對我而言,這是矯枉過正。我只想知道當插入符號是末尾的所有文本輸入框。有沒有簡單的方法來做到這一點?
在所有現代瀏覽器:
//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>
這將檢查插入符號是否在最後,並確保它不僅僅是因爲選擇它顯示結束值。
當你選擇了一些文本時,你不會指定你想要發生什麼,所以在這種情況下,我的代碼只是檢查選擇的末尾是否在輸入的末尾。 (其他答案不會:IE只在版本9中獲得selectionStart
和selectionEnd
)。這是一個跨瀏覽器的功能,可以在IE瀏覽器中工作()(其他答案不會:IE只在版本9中獲得selectionStart
和selectionEnd
)。
現場演示: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;
}
'selectionEnd'總是比'selectionStart'大;你可以放心地使用'selectionEnd'。 – pimvdb
@pimvdb:那麼'selectionEnd'總是和'selectionStart'一樣大。 –
@Tim Down:是的,你是對的。但是,如果它們相等,使用'selectionEnd'仍然是安全的。 – pimvdb