簡體   English   中英

JavaScript querySelector 和 CSS:target 偽類

[英]JavaScript querySelector and CSS :target pseudo-class

我試圖在文檔加載后使用偽類: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()類似的問題

這是基於 WebKit 和 Blink 的瀏覽器的一個已知問題,從未直接解決。 web-platform-tests 建議的解決方法是請求一個 animation 框架,這僅在頁面渲染后發生,此時: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));

這將適用於所有瀏覽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM