如何将光标设置为Internet Explorer中文本INPUT字段的字符串值中的特定位置?(How do I set the cursor to a particular position in

编程入门 行业动态 更新时间:2024-10-21 11:32:14
如何将光标设置为Internet Explorer中文本INPUT字段的字符串值中的特定位置?(How do I set the cursor to a particular position in the string value of a text INPUT field in Internet Explorer?)

我已经在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();

更多推荐

本文发布于:2023-07-04 11:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:光标   字段   设置为   如何将   文本

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!