开发者

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.

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 tec开发者_运维问答hnique:

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.


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();  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜