我想在GWT中找出当前有焦点的元素。基本上,我在我们的应用程序中使用虚拟键盘。除tab键外,所有键都工作正常。如果我得到了focused元素,那么我就可以计算出tab键代码。
在javascript和jquery中,我们可以使用document.activeElement
来获得它。希望有人能让我以正确的方式实现这一目标。
我们将不胜感激。
只有当您的应用程序针对所有浏览器时,"所有浏览器"都不支持它这一事实才很重要。activeElement目前被相当多的浏览器支持。为什么GWT中没有isFocused()?。
我需要类似的东西,我需要从小部件内部知道它是否有焦点。我做了以下
protected native boolean hasFocus(Element element) /*-{
return element.ownerDocument.activeElement == element;
}-*/;
我需要传入当前元素以获得正确的文档,只需调用
document.activeElement;
没有给我我需要的文件。您可能也可以这样做,但传入一个不同的元素(也许是RootPanel元素?),并返回焦点元素而不是bool。
protected native Element elementInFocus(Element element) /*-{
return element.ownerDocument.activeElement;
}-*/;
document.activeElement
并不能在所有浏览器中工作,因此GWT中不支持它。你也许可以使用focus&模糊处理程序来跟踪哪个元素有它。
短模板:
public class IntBox extends com.google.gwt.user.client.ui.IntegerBox {
private boolean focused=false;
public IntBox(){
addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
focused=true;
}
});
addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
focused=false;
}
});
}
public boolean isFocused() {
return focused;
}
}
我们现在可以使用Elemental库来实现这一点。
http://www.gwtproject.org/articles/elemental.html
确切的函数是
elemental.client.Browser.getDocument().getActiveElement()