setSelectionRange解决方法不适用于android 4.0.3

时间:2012-08-17 15:50:00

标签: android cursor

我试图在用户输入时屏蔽电话号码。我已经在android 2.x设备上成功使用了jquery和setTimeout解决方法下面的javascript代码,但我还没有找到适用于android 4.0.3的解决方法。

if (navigator.userAgent.toLowerCase().indexOf("android") >= 0) {
$.fn.usphone = function() {
    this.keyup(function(e) {
        // do not process del, backspace, escape, arrow left and arrow right characters
        var k = e.which;
        if (k == 8 || k == 46 || k == 27 || k == 37 || k == 39)
            return;
        // remove invalid characters
        var value = "";
        for (var i = 0; i < this.value.length; i++) {
            var ch = this.value[i];
            if (ch >= "0" && ch <= "9")
                value += ch;
        }
        // remove extra characters
        if (value.length > 10)
            value = value.substring(0, 10);
        // insert formatting characters
        if (value.length >= 3)
            value = "(" + value.substring(0, 3) + ")" + value.substring(3);
        if (value.length > 5)
            value = value.substring(0, 5) + " " + value.substring(5);
        if (value.length > 9)
            value = value.substring(0, 9) + "-" + value.substring(9);
        // set new value
        var $this = this;
        var length = value.length;
        setTimeout(function() {
            $this.value = value;
            $this.setSelectionRange(length, length);
        }, 0);
    });
};

$('#contact_edit_page, #contact_new_page, #callback_create, #callback_edit, #new_phonecall_contact_page, #new_phonecall').live('pagecreate', function() {
    $('[type^="tel"]').usphone();
});

}

1 个答案:

答案 0 :(得分:1)

我刚遇到同样的问题。我的解决方案如下,

.input {
  -webkit-user-modify: read-write;
}

它适用于我的HTC中的android 4.0.3。