问题描述
我正在为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 App:在Safari中使用JavaScript检测虚拟键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!