zoukankan      html  css  js  c++  java
  • 转:JS在文本域鼠标指定位置插入文本-柯乐义

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JS在文本域鼠标指定位置插入文本-柯乐义</title>
    <script type="text/javascript">
    function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
    sel.select();
    }
    //MOZILLA/NETSCAPE support 
    else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    // save scrollTop before insert www.keleyi.com
    var restoreTop = myField.scrollTop;
    myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    if (restoreTop > 0) {
    myField.scrollTop = restoreTop;
    }
    myField.focus();
    myField.selectionStart = startPos + myValue.length;
    myField.selectionEnd = startPos + myValue.length;
    } else {
    myField.value += myValue;
    myField.focus();
    }
    } 
    </script>
    </head>
    <body>
    <div style="500px;margin-left:auto;margin-right:auto;margin-top:100px;">
    <textarea id="keleyi_com" style="340px; height:180px">
    柯乐义 Javascript 在textarea光标处插入文本
    </textarea>
    <input type="button" onclick="insertAtCursor(document.getElementById('keleyi_com'),'www.keleyi.com')" value="插入文本" />
    </div></body>
    </html>
  • 相关阅读:
    document对象补充
    JavaScript(DOM操作)(Window.document对象)
    DOM、Window操作
    JavaScript基础
    格式布局
    洛谷P2756 飞行员配对方案问题
    洛谷P2526 【SHOI2001】小狗散步
    洛谷P1129 【ZJOI2007】矩阵游戏
    洛谷P1640 【SCOI2010】连续攻击游戏
    二分图
  • 原文地址:https://www.cnblogs.com/laijie/p/4754949.html
Copyright © 2011-2022 走看看