文章标签 ‘操作’

没有评论在文本框or文本域的光标位置操作

2010年4月5日

今天碰上一个同学的需求,记录一下
DEMO:http://www.iamued.com/demo/addtext.html
核心代码如下:

function addText(txt,eid) {
//txt要添加的文本 eid:要操作的文本框,或文本域的id
				obj = document.getElementById(eid);
				selection = document.selection;
				obj.focus();
				if (typeof obj.selectionStart != "undefined") {
				    var s = obj.selectionStart;
					obj.value = obj.value.substr(0, obj.selectionStart) + txt + obj.value.substr(obj.selectionEnd);
					obj.selectionEnd = s + txt.length;
				} else if (selection && selection.createRange) {
					var sel = selection.createRange();
					sel.text = txt;
				} else {
					obj.value += txt;
				}
        }