【问题标题】:Element.prototype.matches not matching naked :pseudoclassElement.prototype.matches 不匹配裸:伪类
【发布时间】:2020-05-17 07:06:55
【问题描述】:

出于某种原因,Element.prototype.matches 对于完全有效的 CSS 选择器 (:hover) 返回 false:

let n = /* an HTMLAnchorElement whose state is forced to :hover */;
console.log(n.matches(':hover')); // false
console.log(n.matches('a:hover')); // true
console.log(n.matches('*:hover')); // false
  • 我在开发工具控制台中运行该代码,找到一个 DOM 节点后,使用 Elements 面板强制其状态为 :hover,然后将 n 设置为 $0
  • n 可以是页面中的任何 HTML dom 节点 - 它不限于锚元素。

此外,使用 document.querySelector 表现出相同的行为 - 但仅在我的本地测试环境中。例如,https://google.com/ 对所有这些测试都返回 true。

【问题讨论】:

  • 请为minimal reproducible example添加相关标记/设置
  • 大概最小的可重现示例是将document.querySelector('.js-add-link').addEventListener('mouseover', ({ target }) => console.log(target.matches(':hover'))) 之类的内容粘贴到控制台中,然后将鼠标悬停在添加评论链接上?我做到了,我对你提供的所有例子都是正确的
  • @OliverRadini 这个问题与鼠标悬停处理程序的关系不大,而与 :hover 选择器有关。我只是在鼠标悬停处理程序中测试它。

标签: javascript google-chrome dom pseudo-class


【解决方案1】:

这是因为我在页面顶部缺少<!DOCTYPE html>。请参阅https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多