textarea 커서 위치 텍스트 삽입

브라우저별 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 len = obj.value.length;
	if (document.selection) {
		var sel = obj.createTextRange();
		sel.moveStart('character',len);
		sel.collapse();
		sel.select();
	} else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
		obj.selectionStart = obj.selectionEnd = len;
	}
}

참조:
http://foxling.org/js-ajax-dom/cross-browser-cursor-position-in-textarea/

좋은 웹페이지 즐겨찾기