对于文本框的输入,有时候会在输入完成之后再在中间插入某些字符,比如图标,这个时候你可能就会想到需要获取光标的位置了。下面介绍这种方法的实现.

JS获取输入框光标位置
所需要的JS文件:输入框获取光标位置JS代码
HTML代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <!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> textrange </title> <script type="text/javascript" src="textarea-editor.js"> </script> </head> <body> <form action="a.cgi"> <textarea id="test" rows="10" cols="50"></textarea> <br/> <a href='#' id="add" value="得到选择区域" unselectable="off">得到选择区域</a> <br/> <input id="text" style="width:100px"/> <input type="button" id="insert" value="光标处插入文本"/> <br/> 开始位置:<input id="start" style="width:100px"/> 结束位置:<input id="end" style="width:100px"/> <a href='#' id="s" value="选择位置" unselectable="off">选择位置</a> <br/> <a value='获得焦点' onclick="tx.focus();return false;" href='#' unselectable="off"/>获得焦点</a> </form> <p>结果:</p> <div style="border:1px solid red;" id="result"></div> <script type="text/javascript"> function $(id) { return document.getElementById(id); } var tx = $("test"),te = new TextareaEditor(tx); var re = $("result"); $("add").onclick = function() { var pos = te.getSelection(); re.innerHTML = ("range : " + pos.selectionStart + " - " + pos.selectionEnd); return false; } $("insert").onclick = function() { te.insertData($("text").value); return false; } $("s").onclick = function() { te.setSelectionRange(parseInt($("start").value), parseInt($("end").value)); return false; } </script> </body> </html> |