iPad Web 应用程序:在 Safari 中使用 JavaScript 检测虚拟键盘? [英] iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

查看:23
本文介绍了iPad Web 应用程序:在 Safari 中使用 JavaScript 检测虚拟键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 iPad 编写一个网络应用程序(不是常规的 App Store 应用程序 - 它是使用 HTML、CSS 和 JavaScript 编写的).由于键盘占据了屏幕的很大一部分,因此在显示键盘时更改应用程序的布局以适应剩余空间是有意义的.但是,我发现无法检测键盘何时或是否显示.

I'm writing a web app for the iPad (not a regular App Store app - it's written using HTML, CSS and JavaScript). Since the keyboard fills up a huge part of the screen, it would make sense to change the app's layout to fit the remaining space when the keyboard is shown. However, I have found no way to detect when or whether the keyboard is shown.

我的第一个想法是假设当文本字段具有焦点时键盘是可见的.但是,当外接键盘连接到 iPad 时,当文本字段获得焦点时,虚拟键盘不会显示.

My first idea was to assume that the keyboard is visible when a text field has focus. However, when an external keyboard is attached to an iPad, the virtual keyboard does not show up when a text field receives focus.

在我的实验中,键盘也没有影响任何 DOM 元素的高度或滚动高度,而且我没有发现指示键盘是否可见的专有事件或属性.

In my experiments, the keyboard also did not affect the height or scrollheight of any of the DOM elements, and I have found no proprietary events or properties which indicate whether the keyboard is visible.

推荐答案

我找到了一个有效的解决方案,虽然它有点难看.它也不适用于所有情况,但对我有用.由于我将用户界面的大小调整为 iPad 的窗口大小,因此用户通常无法滚动.换句话说,如果我设置了窗口的scrollTop,它就会保持在0.

I found a solution which works, although it is a bit ugly. It also won't work in every situation, but it works for me. Since I'm adapting the size of the user interface to the iPad's window size, the user is normally unable to scroll. In other words, if I set the window's scrollTop, it will remain at 0.

另一方面,如果显示键盘,滚动会突然起作用.所以我可以设置scrollTop,立即测试它的值,然后重置它.以下是使用 jQuery 的代码中的样子:

If, on the other hand, the keyboard is shown, scrolling suddenly works. So I can set scrollTop, immediately test its value, and then reset it. Here's how that might look in code, using jQuery:

$(document).ready(function(){
    $('input').bind('focus',function() {
        $(window).scrollTop(10);
        var keyboard_shown = $(window).scrollTop() > 0;
        $(window).scrollTop(0);

        $('#test').append(keyboard_shown?'keyboard ':'nokeyboard ');
    });
});

通常,您希望用户看不到此内容.不幸的是,至少在模拟器中运行时,iPad 明显(虽然很快)再次上下滚动.尽管如此,它仍然有效,至少在某些特定情况下是这样.

Normally, you would expect this to not be visible to the user. Unfortunately, at least when running in the Simulator, the iPad visibly (though quickly) scrolls up and down again. Still, it works, at least in some specific situations.

我已经在 iPad 上测试过了,它似乎工作正常.

I've tested this on an iPad, and it seems to work fine.

这篇关于iPad Web 应用程序:在 Safari 中使用 JavaScript 检测虚拟键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆