我有一个基于 GWT 的应用程序,当我的鼠标悬停在某个元素上时,我希望在该特定元素上触发 getClass() 方法,以在 TooTip 中显示类名。我想为页面上的每个元素自动执行此过程。因此,如果我有一种方法可以告诉我鼠标悬停在哪个元素上,我的工作就完成了。请帮忙。
最佳答案
Adam 出色答案的替代方案,以完全相反的方式构建 - 不是查看每个 Widget 的根元素并对其进行调整,而是监视整个文档上的 mouseover
事件,并尝试找出它在哪个小部件中,尽管我实际上没有实现工具提示,只是暂时的 console.log 消息。
原则是从事件发生的元素开始,检查每个父元素,直到发现有一个 Widget 附加到它,然后记录该详细信息(或者,如果没有找到与此匹配的父元素,则停止。
这种方法有两个小优点:它不会改变每个 Widget 元素的 title
属性,而且它甚至可以在最初设置后添加的 widget 上工作,而不是要求它是重新运行。缺点:这对小部件如何附加进行了一些假设,使用 GWT 内部而不是实际遍历小部件层次结构,并且它可能会记录一些 UIObjects 或其他事件处理程序(尽管这些很少是小部件以外的东西,并且如果这种行为确实如此)如果不需要,可以添加 instanceof Widget
检查)。
Event.addNativePreviewHandler(e -> {
// Listen to all events before a widget gets the chance, only handle the "mouseover".
// Depenending on which ToolTip is used, a "mouseout" handler might be desirable too,
// to hide the tooltip, or else just use a single instance and move it around the page
// as needed
if (e.getTypeInt() != Event.ONMOUSEOVER) {
return;
}
// If the event somehow happens to a non-element, ignore
EventTarget eventTarget = e.getNativeEvent().getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
// examine each node up the hierarchy until a parent is found, or we run out of options
Element elt = eventTarget.cast();
// Could also add that instanceof check here, ignore non-Widgets
while (DOM.getEventListener(elt) == null) {
elt = elt.getParentElement();
if (elt == null) {
// give up
return;
}
}
// Whatever we've found is attached to that element to handle events like a widget would.
// Other examples include UIObjects (like tree nodes) or GQuery event listeners
Object attachedObject = DOM.getEventListener(elt);
// Log it (assumes elemental2, could just as easily use GWT.log()
// but really should be replaced by your preferred ToolTip
DomGlobal.console.log(attachedObject.getClass());
});
这也可以很容易地在纯 JS 中实现,以允许检查使用 Widget 的正在运行的 GWT 应用程序 - getEventListener 只是在元素上查找 __listener
属性,以及大多数其他行或多或少直接翻译成JS。 getClass()
方法是唯一有问题的方法,具体取决于应用程序的编译方式。
关于java - 如何知道我的鼠标悬停在 GWT 中的哪个组件上? [JAVA],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367920/