Android web browser 中text box 使用setSelectionRange无效的问题(caret positionning)

事件起因是做web app用了一个jquery插件jquery.maskinput,这个插件是一个文本格式化插件,在桌面浏览器上都是ok的,并且在ipad上的safari都没问题,问题出现在了android浏览器上,我测试的机型是2.3的系统,按照我查到的资料是在2.3及以下的系统的浏览器中使用这个setSelectionRange其实都是会有问题的。

问题描述:使用setSelectionRange(start,end)去设置移动文本框中的光标,光标显示已经移动,但是实际上是并没有移动的,你再输入一个值的时候,会发现文本出现的位置是光标未移动前的位置,具体的图片描述在这里有一个类似的:Issue 15245

使用这个方法是在keyPress事件中,当你设置完setSelectionRange后,马上使用查 selectionStart和selectionEnd,这时候显示的值是正确的,但下一次keypress事件再触发时,你再查selectionStart和selectionEnd时就会发现值根本没有被设置上去,上代码看看吧

$('#txtId').bind('keypress',function(){
    var start = this.selectionStart,
          end = this.selectionEnd;
    console.log('before set start :'+start+' ,end :'+end);
    this.setSelectionRange(start+2,end+2);
    console.log('set later start :'+this.selectionStart+',end :'+this.selectionEnd);
});

这段代码在桌面浏览器执行时输入的情况和在android的浏览器上执行时输出是不一样的,就像我上面描述的那样。

在maskinput中我改了这个插件的代码来修复这个问题,具体是将上一次设置的值存起来,下次使用的时候判断是否使用。唉,不知道在android4.0的时候这个问题修复了没有。

 2012-6-27

新的解决方案

var that = this;
setTimeout(function(){
    that.setSelectionRange(start,end);
},10);

  

使用setTimeout去设置setSelectionRange,这样可以起到一定作用,但是经我测试,如果输入过快,还是会有之前的问题,但是,正常输入已经可以解决该问题了。

 

参考链接:http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#the-selection

    http://digitalbush.com/2010/12/22/state-of-the-masked-input-plugin/comment-page-2

           http://code.google.com/p/android/issues/detail?id=15245

          http://help.dottoro.com/ljtfkhio.php

          https://github.com/digitalBush/jquery.maskedinput/issues/55

posted @ 2012-06-01 18:02  Bodil  阅读(2200)  评论(1编辑  收藏  举报