我已经在Firefox,Safari和Chrome中使用它了。
我希望能够以编程方式在Internet Explorer的INPUT字段中设置文本光标的位置。
我在各种网站上查看了这个主题,并且通常发现了相同的技术:
var el = document.getElementById("myTextField"); var pos = 6; if (document.selection) { el.focus(); var selection = document.selection.createRange(); selection.moveStart("character", -el.value.length); selection.moveStart("character", pos); selection.moveEnd("character", 0); selection.select(); }问题是,当我尝试这样做时,无论我提供什么位置,光标总是会到达值的末尾。
我误解了人们一直在使用的技术吗? 我在某处错过了什么吗? 这有点令人沮丧,但当然这是使用这些不同浏览器进行Web开发的本质。
在此先感谢您的帮助。
I already have this working in Firefox, Safari and Chrome.
I would like to be able to programmatically set the position of the text cursor within an INPUT field in Internet Explorer.
I looked this topic up on various websites and generally found the same technique:
var el = document.getElementById("myTextField"); var pos = 6; if (document.selection) { el.focus(); var selection = document.selection.createRange(); selection.moveStart("character", -el.value.length); selection.moveStart("character", pos); selection.moveEnd("character", 0); selection.select(); }The problem is that when I try to do this the cursor always goes to the end of the value regardless of what position I provide.
Did I misunderstand the technique people have been using? Did I miss something somewhere? It's a little bit frustrating, but of course that's the nature of web development with these different browsers.
Thanks in advance for any help.
最满意答案
以下代码在IE 9中适用于我
<script type="text/javascript"> var input = document.getElementById("myInput"); input.selectionStart = 2; input.selectionEnd = 5; </script>这是我用于IE 6的代码
input.select(); var sel = document.selection.createRange(); sel.collapse(); sel.moveStart('character', this.SelectionStart); sel.collapse(); sel.moveEnd('character', this.SelectionEnd - this.SelectionStart); sel.select();The following code is working for me in IE 9
<script type="text/javascript"> var input = document.getElementById("myInput"); input.selectionStart = 2; input.selectionEnd = 5; </script>Here is the code that I'm using for IE 6
input.select(); var sel = document.selection.createRange(); sel.collapse(); sel.moveStart('character', this.SelectionStart); sel.collapse(); sel.moveEnd('character', this.SelectionEnd - this.SelectionStart); sel.select();更多推荐
发布评论