使用jQuery在iPhone和iPad浏览器上无法在焦点上选择文本

5
我们正在开发适用于移动浏览器的Web应用程序,我们希望每当输入框获得焦点时,输入框中的文本都会被选中。下面的答案修复了桌面Chrome/Safari浏览器的问题。以下解决方案在Android浏览器上运行良好,但在iPhone/iPad浏览器上无法使用,是否有解决方案?
$("#souper_fancy").focus(function() { $(this).select() });

$("#souper_fancy").mouseup(function(e){
        e.preventDefault();
});

参考:

在Safari和Chrome中使用jQuery选择文本时无法工作的解决方法


3
尝试访问 https://dev59.com/Z3A75IYBdhLWcg3weZDu。该链接提供了有关在iOS设备上的Mobile Safari浏览器中编程选择输入字段文本的信息。 - robocat
1
是的。谢谢Robcat,它起作用了,在这里找到了解决方案- https://dev59.com/Z3A75IYBdhLWcg3weZDu - Anand
4个回答

4

这里找到了答案,但我不知道如何将此问题标记为重复。 在iOS设备(移动Safari)上以编程方式选择输入字段中的文本

我的解决方案看起来像这样:

<script type="text/javascript">
           $('div,data-role=page').live('pageshow', function (event) {
               jQuery.validator.unobtrusive.parse(".ui-page-active form");
               $("input[type='text'], textarea, input[type='password'], input[type='number']").live('mouseup', function (e) { e.preventDefault(); });
               $("input[type='text'], textarea, input[type='password'], input[type='number']").live('focus', function () {this.setSelectionRange(0, 9999); });             
           });       
    </script>

1

您可以使用document.execCommand('selectAll');。但是,如果用户滚动页面,将会显示复制/粘贴菜单。

这是我使用的方法:

function trySelect(el, evenInactive, select_ios) {
    var select = function() {
        try {
            if (mojo.isTouch && select_ios && core.iosDevice && mojo.isInput(el) && document.execCommand) {
                document.execCommand('selectAll');
            } else {
                el.select();
            }
        } catch (e) {
        }
    };
    if (el && el.select && !el.disabled && (!el.readOnly || el.selectReadOnly) && mojo.isInput(el)) {
        if (evenInactive || mojo.activeElement() === el) {
            if (mojo.isTouch && core.webkitVer) {   // http://code.google.com/p/chromium/issues/detail?id=32865
                setTimeout(select, 0);
            } else {
                select();
            }
        }
    }
}

这引用了一些内部函数:

  • mojo.isTouch - 触摸设备为真
  • core.iosDevice - iOS 设备为真
  • mojo.isInput - 测试输入元素
  • mojo.activeElement() - document.activeElement

编辑:document.execCommand('selectAll'); 不应使用,而应改用 el.setSelectionRange(0, el.value.length);。在 iOS5 上似乎可以正常工作... 在 iOS4 上可能无法正常工作(我没有 iOS4 设备进行测试)。


1

-1

这个对我有效。

        $("input[type='text'],select,textarea").focus(function () {
            $(this).addClass('text-focus');
        });

        $("input[type='text'],select,textarea").blur(function () {
            $(this).removeClass('text-focus');
        });

       .text-focus
       {
       border: 1px solid #ea9a00;
       }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接