【问题标题】:document.querySelectorAll with the pseudo-class :hover not working in FF or IE带有伪类的 document.querySelectorAll :hover 在 FF 或 IE 中不起作用
【发布时间】:2013-10-17 03:37:57
【问题描述】:

我想获取光标下的元素。当我使用document.querySelectorAll(":hover"); 时,它在 Chrome 中运行良好,但在 Firefox 或 IE 中无法运行。

这可能是因为我在 Google 地图的 eventListener 中使用了它。这里是我如何使用它。

google.maps.event.addListener(polygon,"mouseout",function(){
  elementHover = document.querySelectorAll( ":hover" );
  alert(elementHover[elementHover.length-1].id);
});

在 Chrome 中,它为我提供了我用光标悬停的元素的 ID,但在 IE 或 FF 中我什么也得不到。

【问题讨论】:

  • 在 IE10 和 FF23 中为我工作 --- 测试 setInterval(function(){console.log(document.querySelectorAll(":hover").length);}, 5*1000)跨度>

标签: javascript cross-browser pseudo-class selectors-api


【解决方案1】:

您使用 mouseout 而不是 mouseover 有什么原因吗?看起来,取决于浏览器如何解决它(它是在您离开之前触发事件,还是在您离开之后触发事件,正在侦听事件的对象?),这可能会引起一些恐慌。您是否有理由不只是传递 Event 对象来获取您要离开的对象,而不是希望选择器会触发?

根据 Google 的文档 (https://developers.google.com/maps/documentation/javascript/events#EventArguments),您可以将事件对象传递给函数:

google.maps.event.addListener(polygon,"mouseout",function(evt){
  // get the target from the mouseout event, something like this:
  elementHover = evt.target;
  alert(elementHover[elementHover.length-1].id);
});

目前我无法对此进行测试,因此您可能不得不摆弄它并阅读 Google 的文档,以确保您正在查看的事件为您提供了对它来自的对象的引用(您甚至可以使用“this”而不是 evt.target,具体取决于传递到上下文中的内容)。但是, :hover 仍然是一个半飞行的野兽,并且根据解决事件的顺序,您很可能只在 Chrome 中看到它,因为它触发事件的方式与 FF 和 IE 不同。

祝你好运!

【讨论】:

  • 我需要使用 mouseout 事件,因为当光标移动到除某个 DIV 之外的所有位置时,该事件需要修改多边形。我查看了文档并进行了研究。我得到的解决方案是使用 evt.Va.toElement(如果它在 Chrome 或 IE 上)和 evt.Va.relatedTarget(对于 FF)。谢谢!
  • 太棒了!很高兴您能找到可行的解决方案!
猜你喜欢
  • 1970-01-01
  • 2011-01-05
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2011-09-28
  • 2013-04-12
  • 1970-01-01
相关资源
最近更新 更多