javascript - 我如何在 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();
}
问题是,当我尝试这样做时,光标总是会跳到值的末尾,而不管我提供的位置是什么。
我是不是误解了人们一直在使用的技术?我是不是在某个地方漏掉了什么?这有点让人沮丧,但当然,这就是使用不同浏览器进行网页开发的本质。
提前感谢您的任何帮助。
答案#1
以下代码在我的 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();
