【问题标题】:IE 8: move caret to the end of a text input field AND make the end visibleIE 8:将插入符号移动到文本输入字段的末尾并使结尾可见
【发布时间】: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


    【解决方案1】:

    我想我找到了 IE8 的解决方案(我只在 IE8 中测试过)。见fiddle

    这是一段JS代码:

    var rng = text.createTextRange();
    rng.moveEnd( 'textedit' );
    rng.moveStart( 'textedit' );
    rng.select();
    rng.scrollIntoView();
    

    【讨论】:

    • 我认为这可能会奏效。我找到了另一个解决方案,我最终使用了它。见上面的 cmets。
    猜你喜欢
    • 2011-02-11
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    相关资源
    最近更新 更多