简体   繁体   English

如何将光标设置为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?

I already have this working in Firefox, Safari and Chrome. 我已经在Firefox,Safari和Chrome中使用它了。

I would like to be able to programmatically set the position of the text cursor within an INPUT field in Internet Explorer. 我希望能够以编程方式在Internet Explorer的INPUT字段中设置文本光标的位置。

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. 这有点令人沮丧,但当然这是使用这些不同浏览器进行Web开发的本质。

Thanks in advance for any help. 在此先感谢您的帮助。

The following code is working for me in IE 9 以下代码在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 这是我用于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();  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM