表單功能: 游標保持在文字最後, 方便繼續輸入文字

這個功能用到我沒接觸過的語法,

且有做瀏覽器間的相容性,

值得學習,


完整code:

<body>
<h2>游標永遠停留在文字最後</h2>
<input type="text" id="cursorPos" value="游標永遠停留在文字最後">

<script>
window.onload = function() {
var cursorPos = document.getElementById("cursorPos");
cursorPos.onclick = cursorPos.onkeyup = function() {      // 用2種事件是為了達最大相容性,  因為onfocus有瀏覽器相容性問題
var _vLen = this.value.length;
if (this.setSelectionRange) {                                             // 非IE寫法
this.setSelectionRange(_vLen, _vLen);
} else {                                                                                    //  IE寫法
var a = this.createTextRange();
a.moveStart("character", _vLen);
a.collapse(true);
a.select();
}
};
};
</script>
</body>


以下說明語法,

setSelectionRange():

--> The HTMLInputElement.setSelectionRange() method sets the start and end positions of the current text selection in an <input> element.

--> Syntax:
inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);

HTMLInputElement.setSelectionRange():
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange


createTextRange(): (IE限定)

--> Creates a TextRange object for the element.

--> Syntax:
object.createTextRange();

createTextRange method:
https://msdn.microsoft.com/zh-tw/library/ms536401(v=vs.85).aspx


moveStart(): (IE限定)

--> Changes the start position of the range.

--> Syntax:
var retval = TextRange.moveStart(Unit, Count);

moveStart method:
https://msdn.microsoft.com/en-us/library/ms536623(v=vs.85).aspx


collapse(): (IE限定)

--> Collapses (or removes) a range by moving the insertion point to the beginning or end of the current range.

--> Syntax:
var retval = Range.collapse(toStart);

collapse():
https://msdn.microsoft.com/en-us/library/ff975439(v=vs.85).aspx


select(): (IE限定)

--> Makes the selection equal to the current object.

--> Syntax:
object.select();

select():
https://msdn.microsoft.com/en-us/library/ms536735(v=vs.85).aspx



最後, 如果今天不能用表單元素, 如input, 來製作以上效果時,

這篇文章寫的滿好的, 值得好好看一下,

自動選取某個區域的文字:
http://www.oxxostudio.tw/articles/201508/select-text.html



留言

熱門文章