【发布时间】:2013-12-11 04:54:25
【问题描述】:
我正在尝试在文本框中设置光标/插入符号的位置,使其位于输入控件文本内容的末尾。有很多这样做的例子。棘手的部分是如果文本超出文本框的宽度,我希望文本“滚动”到视图中,以便文本的结尾和插入符号可见。这正是这个问题所要问的:
move caret to the end of a text input field AND make the end visible
那里列出了一个适用于 Chrome 和可能更高版本的 IE(9 或更高版本)的解决方案,但对于 IE 8,该解决方案不起作用;没有document.createEvent。我尝试修改代码以便使用 createEventObject 和 fireEvent:
window.setTimeout(function() {
e = document.createEventObject("KeyboardEvent");
e.keyCode = 35;
//textfield.fireEvent('onkeypress', e);
textBox.fireEvent('onkeydown', e);
textBox.fireEvent('onkeyup', e);
textBox.blur();
textBox.focus();
}, 2000);
但这并没有提供将文本末尾水平滚动到视图中的预期效果。 IE 8 有没有办法做到这一点?
谢谢!
巴黎
编辑:最后,我使用了这个功能,根据我的测试,它似乎适用于所有主要浏览器。
scrollCaretIntoView: function(textField) {
if (textfield.selectionStart || textfield.selectionStart === 0) {
//For all browsers, except IE 8 and earlier
textfield.selectionStart = textfield.value.length;
textfield.selectionEnd = textfield.value.length;
textfield.blur(); // Webkit wake-up hack
textfield.focus();
} else if (document.selection) {
//IE8 and earlier specific code
textfield.focus();
var range = document.selection.createRange();
range.moveEnd('character', 0); //move 0 characters from current position
range.select();
}
}
【问题讨论】:
标签: javascript internet-explorer internet-explorer-8