使用Js 获取鼠标的当前位置,可以让我们在文本区域指定位置插入所需要的值。例子如下
主程序:index.php
主程序:index.php
- <script>
- var start=0;
- var end=0;
- function add(){
- var textBox = document.getElementById("ta");
- var pre = textBox.value.substr(0, start);
- var post = textBox.value.substr(end);
- textBox.value = pre + document.getElementById("inputtext").value + post;
- }
- function savePos(textBox){
- if(typeof(textBox.selectionStart) == "number"){
- start = textBox.selectionStart;
- end = textBox.selectionEnd;
- }
- else if(document.selection){
- var range = document.selection.createRange();
- if(range.parentElement().id == textBox.id){
- // create a selection of the whole textarea
- var range_all = document.body.createTextRange();
- range_all.moveToElementText(textBox);
- for (start=0; range_all.compareEndPoints("StartToStart", range) < 0; start++)
- range_all.moveStart('character', 1);
- for (var i = 0; i <= start; i ++){
- if (textBox.value.charAt(i) == '/n')
- start++;
- }
- // create a selection of the whole textarea
- var range_all = document.body.createTextRange();
- range_all.moveToElementText(textBox);
- // calculate selection end point by moving beginning of range_all to end of range
- for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end ++)
- range_all.moveStart('character', 1);
- // get number of line breaks from textarea start to selection end and add them to end
- for (var i = 0; i <= end; i ++){
- if (textBox.value.charAt(i) == '/n')
- end ++;
- }
- }
- }
- document.getElementById("start").value = start;
- document.getElementById("end").value = end;
- }
- </script>
- 下面是在页面中调用js代码的方法:
- <form action="a.cgi">
- <table border="1" cellspacing="0" cellpadding="0">
- <tr>
- <td>start: <input type="text" id="start" size="3"/></td>
- <td>end: <input type="text" id="end" size="3"/></td>
- </tr>
- <tr>
- <td colspan="2">
- <textarea id="ta" onKeydown="savePos(this)"
- onKeyup="savePos(this)"
- οnmοusedοwn="savePos(this)"
- οnmοuseup="savePos(this)"
- οnfοcus="savePos(this)"
- rows="14" cols="50"></textarea>
- </td>
- </tr>
- <tr>
- <td><input type="text" id="inputtext" /></td>
- <td><input type="button" onClick="add()" value="Add Text"/></td>
- </tr>
- </table>
- </form>