JavaScript querySelector 和 CSS :target 伪类

问题描述

我试图在文档加载后使用伪类 :target 获取目标元素。 我创建了以下示例来说明问题。

<!DOCTYPE html>
<html>
    <head>
        <script>
            document.addEventListener("DOMContentLoaded",function(){
                console.log(document.querySelector(":target"));
            });
        </script>
    </head>
    <body>
        <div id="test"></div>
    </body>
</html>

如果我加载 test.html,则控制台输出

null

如果我在 Chrome 和 Opera 上加载 test.html#test,则控制台输出

null

如果我在 Firefox 和 IE11 上加载 test.html#test,则控制台输出

<div id="test"></div>

我的问题是:

  1. 哪些浏览器具有正确的行为?
  2. DOMContentLoaded调用 querySelector(":target") 的正确事件吗?
  3. 是否有其他方法可以在文档加载后获取目标元素?

PS:感谢 setTimeout,我成功地解决了 Chrome 和 Opera 上的问题,但这不是一个好的解决方案。有人有更好的主意吗?

编辑:我发现 JQuery Selecting :target on document.ready()

存在类似问题

解决方法

这是一个 known issue,基于 WebKit 和基于 Blink 的浏览器从未被直接解决过。 web-platform-tests 建议的解决方法是 request an animation frame,这仅在页面呈现后发生,此时 :target 伪似乎匹配成功:

async_test(function() {
  var frame = document.createElement("iframe");
  var self = this;
  frame.onload = function() {
    // :target doesn't work before a page rendering on some browsers.  We run
    // tests after an animation frame because it may be later than the first
    // page rendering.
    requestAnimationFrame(self.step_func_done(init.bind(self,frame)));
  };
  frame.src = "ParentNode-querySelector-All-content.xht#target";
  document.body.appendChild(frame);
})

我的测试表明,简单地使用 onload 效果很好,但作者可能正在做一些事情,此外,对 requestAnimationFrame() 的一次调用几乎没有任何成本,因此您也可以效仿。

以下测试使用 onload(与 DOMContentLoaded 相反,后者在 DOM 树构建后立即触发但不一定呈现):

data:text/html,<!DOCTYPE html><script>window.onload=function(){console.log(document.querySelector(":target"));};</script><div id="test"></div>#test

以下测试将 requestAnimationFrame()onload 结合使用:

data:text/html,<!DOCTYPE html><script>window.onload=requestAnimationFrame(function(){console.log(document.querySelector(":target"));});</script><div id="test"></div>#test
,

看起来 Firefox 具有理想的行为,但可能不是正确的行为。

不过,作为替代,您可以使用:

document.addEventListener('DOMContentLoaded',() => document.querySelector(window.location.hash));

这将适用于所有浏览器。