首页 > web前端 > js教程 > JS在TextArea光标位置插入文字并实现移动光标到文字末尾_javascript技巧

JS在TextArea光标位置插入文字并实现移动光标到文字末尾_javascript技巧

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
发布: 2016-05-16 17:31:46
原创
1524 人浏览过

=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;
}
}

复制代码 代码如下:



复制代码 代码如下:


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
php 中textarea 如何实例化调用umeditor
来自于 1970-01-01 08:00:00
0
0
0
angular.js - Angularjs设置textarea内的默认内容
来自于 1970-01-01 08:00:00
0
0
0
css - 如何控制 textarea 的 img tag?
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板