【问题标题】:Detect when a css rule has been applied from a JS added stylesheet检测何时从 JS 添加的样式表应用了 CSS 规则
【发布时间】:2020-07-18 21:57:41
【问题描述】:

之前可能已经提出过问题,但截至目前还没有满意的答案 2020.

鉴于此示例

 `.bar { height: ${randomHeight()}px }`

然后作为 style tag 插入到 HEAD 元素中。

成为:

<style rel="stylesheet" type="text/css" id="116">
    .bar { height: 112px }
</style>

举个例子。

现在,这不会立即生效,因此在将其插入文档后,我将无法记录例如条形的高度。

但是,如果我 setTimeout(..., 1000) 我最终可以读取元素的高度。

ANY 样式标签被插入时,有 一种方法 侦听检测 >已应用,而不诉诸任意 setTimeout?

只对这种高度情况不感兴趣,而是应用了任何添加的样式表的通用解决方案。

【问题讨论】:

  • 这个问题感觉就像the XY problem,因为你的问题似乎集中在一个合法的解决方案上,而不是一个hack。你能描述一下你的用例吗?

标签: javascript css


【解决方案1】:

您可以使用MutationObserver 来监视对 DOM 树所做的更改。确保在将样式标记插入 HEAD 之前运行下面的 sn-p,以便它可以捕获更改。

// Select the node that will be observed for mutations
const targetNode = document.getElementsByTagName('head')[0];

// Options for the observer (which mutations to observe)
// Set childList to true as we want to observe if style tag has been added as a child of the head element.)
const config = { attributes: false, childList: true, subtree: false };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    for (let mutation of mutationsList) {
        if (mutation.addedNodes.length && mutation.addedNodes[0].tagName.toLowerCase() === 'style') {
            console.log('A style tag has been added to the HEAD:', mutation.addedNodes[0]); 
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

【讨论】:

    【解决方案2】:

    我想到了一个替代的答案,一个不需要轮询的,你可以使用动画结束事件,这是一个css动画结束时触发的事件。

    您可以在此处了解有关此活动的更多信息,https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多