编程语言
首页 > 编程语言> > javascript – 如何将光标设置为Internet Explorer中文本INPUT字段的字符串值中的特定位置?

javascript – 如何将光标设置为Internet Explorer中文本INPUT字段的字符串值中的特定位置?

作者:互联网

我已经在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开发的本质.

在此先感谢您的帮助.

解决方法:

以下代码在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();  

标签:javascript,internet-explorer,cursor,selection,textinput
来源: https://codeday.me/bug/20190626/1294970.html