点击文本框中选中文本,得到的光标位置不正确?
HTML code<script type="text/javascript"> function Test(str) { document.getElementById("test").innerHTML += str; }; function GetPos(obj) { obj.focus(); var s=document.selection.createRange(); s.setEndPoint("StartToStart",obj.createTextRange()) Test(s.text.length); };</script><input type="text" size="16" onclick="GetPos(this)" value="123456789" />onclick选中字符<br /><input type="text" size="16" onmouseup="GetPos(this)" value="123456789" />onmouseup选中字符<hr />test:<span id="test"></span><hr />例如,用鼠标选中“4567”四个字符,只要是点击在选中字符上,获取的光标位置就不正确。而且onclick和onmouseup得到的值不一样。</body>
------解决方案--------------------
因为mouseup的时候,selection还没有改变,你获取的仍然是先前的range. 你可以setTimeout来处理。
查询谷 - www.chaxungu.com
点击文本框中选中文本,得到的光标位置不正确?该怎么解决
编辑:chaxungu时间:2022-10-02 23:15:50分类:web开发