gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:53 26 4
gpt4 key购买 nike

我已经在 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 中文本 INPUT 字段的字符串值中的特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6822443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com