前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >textarea 在光标处插入文字

textarea 在光标处插入文字

作者头像
deepcc
发布2018-05-16 15:33:52
1.1K0
发布2018-05-16 15:33:52
举报
文章被收录于专栏:deepccdeepcc
效果演示

欢迎访问cssfirefly.cnblogs.com

html:

代码语言:javascript
复制
<textarea id="text" style="width:500px;height:80px;">欢迎访问http://cssfirefly.cnblogs.com/</textarea>

<input type="button" value="插入文字" onclick="insertText(document.getElementById('text'),' NewWord ')">
<input type="button" value="插入文字" onclick="moveEnd(document.getElementById('text'))">

js:

代码语言:javascript
复制
代码如下:
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;
    }
} 

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-08-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 效果演示
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档