JavaScript获取焦点并将光标移动到末尾字符

测试和使用环境:
Google Chrome浏览器,手动触发焦点事件(如按键盘↑键)
代码如下:
function focusOn(_textarea, moveToLast){
    this.moveToLastFlag = moveToLast;
    function moveToTextEnd() {
        if (this.moveToLastFlag){
            if (typeof _textarea.selectionStart == "number") {
                _textarea.selectionStart = _textarea.selectionEnd = _textarea.value.length;
            } else if (typeof _textarea.createTextRange != "undefined") {
                _textarea.focus();
                var range = _textarea.createTextRange();
                range.collapse(false);
                range.select();
            }
        }
    }

    _textarea.focus();
    _textarea.onfocus = function(e){
        moveToTextEnd();
        // Work around Chrome's little problem
        if (window.chrome){
            window.setTimeout(function() {
                moveToTextEnd();
            }, 1);
        }
    }

}

参考 http://jsfiddle.net/ghAB9/3/

附键盘监听代码
        document.onkeydown = function(e){
            switch (e.which){
                case 9:     //tab

                    break;
                case 13:    //enter

                    break;
                case 38:    //up
                    
                    break;
                case 40:    //down
                    
                    break;
            }

        };

猜你喜欢

转载自fengjianrong.iteye.com/blog/2308207