TextArea光标位置插入文字

需要实现:在光标位置处插入文字,以及获取焦点后光标位置处于文字末尾。
以前一直没有做过,今天了解了一下后实现并记录在此。

各浏览器TextArea获得焦点后的光标位置情况:

textarea.focus()
  • FireFox: 所有文字结束处
  • IE: 文字开头
  • Opera: 文字开头
  • Chrome: 文字开头
  • Safari: 文字开头

IE支持document.selection
Firefox,Chrome,Safari以及Opera都有selectionStart和selectionEnd属性
针对浏览器的特性进行判断并实现,代码如下:

function insertText(obj,str) {
	obj.focus();
	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;
	}
}

Demo猛击这里

关于IE TextRange 对象的方法与属性介绍:
http://msdn.microsoft.com/zh-cn/library/ms535872%28en-us,VS.85%29.aspx

TextArea对象的属性:
https://developer.mozilla.org/en/DOM/TextArea

发表评论

Your email is never shared. Required fields are marked *

*
*