简体   繁体   English

如何从HTMLLinkElement获取CSSStyleSheet

[英]How to get CSSStyleSheet from a HTMLLinkElement

I want to have a better CSS variable control through JavaScript, which requires to operate on a CSSRule object. 我想通过JavaScript获得更好的CSS变量控制,这需要对CSSRule对象进行操作。

Here's the JavaScript code of 2 ways to get it: 这是两种获取方法的JavaScript代码:

// get from the CSSStyleSheet of a <style> element
document.getElementsByTag('style')[0].sheet.rules;
// direct way
document.styleSheets[0].rules;

I've written the CSS in a file, so I have to get it through a element. 我已经将CSS写入文件中,因此必须通过一个元素来获取。

However, I found that you can only get a CSSStyleSheet object with a null CSSRule from elements. 但是,我发现您只能从元素中获取具有null CSSRule的CSSStyleSheet对象。

link_ele.sheet.rules;  // null

I'm st(f)ucked. 我很生气。

Console output 控制台输出

// btw i've tried this method , but it's just ain't workin' (returns an empty array), thx for tellin' tho @SamuilPetrov //顺便说一句,我已经尝试过此方法 ,但是它只是行不通(返回一个空数组),请告诉@SamuilPetrov

I've found the solution for this situation: You can simply overwrite the style sheet with a created element. 我已经找到了针对这种情况的解决方案:您可以简单地使用创建的元素覆盖样式表。

let style = { };
let setCSSVariable = (name, value) => style.rules.setProperty('--' + name, value);
document.addEventListener('DOMContentLoaded', function() {
    style.element = document.createElement('style');
    document.head.appendChild(style.element);

    style.sheet = style.element.sheet;
    style.sheet.insertRule(/* CSS selector */);

    style.rules = style.sheet.cssRules[0].style;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM