Tag Archives: selectionStart
需要實現:在光標位置處插入文字,以及獲取焦點後光標位置處於文字末尾。
以前一直沒有做過,今天瞭解了一下後實現並記錄在此。
各瀏覽器TextArea獲得焦點後的光標位置情況:
textarea.focus()
FireFox: 所有文字結束處
IE: 文字開頭
Opera: 文字開頭
Chrome: 文字開頭
Safari: 文字開頭
IE支持document.selection
Firefox,Chrome,Safari以及Opera都有selectionStart和selectionEnd屬性
針對瀏覽器的特性進行判斷並實現,代碼如下:
function insertText(obj,str) {
if (document.selection) {
var sel = document.selection.createRange();
sel.text = str;
} else if (typeof obj.selectionStart === ‘number’ && typeof obj.selectionEnd === ‘number’) {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
} else {
obj.value += str;
}
}
function moveEnd(obj){
obj.focus();
var [...]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.