在光标选中位置插入文字js
2015-08-12 17:14
696 查看
//调用方法
insertText(document.getElementById('codeTextarea'), "{GD_" + name + "}")
//获取文本框中光标的位置
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;
}
}
insertText(document.getElementById('codeTextarea'), "{GD_" + name + "}")
//获取文本框中光标的位置
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;
}
}
相关文章推荐
- js如何查看元素类型
- js正则表达式test()和exec()用法实例
- js正则表达式实例(汇总)
- <a>标签中href="javascript:;"表示什么意思?
- js获取自定义属性值
- 原生JS开发酷炫版飞机大战源码下载仅此一家
- Webform & JavaScript
- JavaScript常用字符串处理方法
- Extjs中的success和failure
- JavaScript中的call方法和apply方法使用对比
- js_鼠标点击事件:简单全选功能
- javascript中Math ceil(),floor(),round()三个函数的对比
- js笔记
- Javascript 面向对象
- 从本地JSON文件中读取数据
- 一张地图告诉你,只JavaScript不够!
- js实现图片轮播效果
- JS学习第九天----数组
- 详细解读JavaScript的跨浏览器事件处理
- javascript ipz127