js 将光标移动到textarea的最后和光标位置插入内容

来源:互联网 发布:php 文章编辑发布系统 编辑:程序博客网 时间:2024/04/29 19:26

js 将光标移动到textarea的最后和光标位置插入内容

IE支持document.selection
Firefox,Chrome,Safari以及Opera都有selectionStart和selectionEnd属性

原文:http://www.cnblogs.com/yoyiorlee/archive/2011/04/04/2005213.html

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://www.51xuediannao.com/qd63/index.php/page-2-81-1.html

0 0
原创粉丝点击