Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hello, Construct Stylesheets #59

Open
gogoend opened this issue Sep 14, 2020 · 1 comment
Open

Hello, Construct Stylesheets #59

gogoend opened this issue Sep 14, 2020 · 1 comment
Labels

Comments

@gogoend
Copy link
Owner

gogoend commented Sep 14, 2020

近期,笔者的电脑自动更新了 Chrome 浏览器,升级到了 85 版本。笔者在开发者工具中展示的 What's New 选项卡里发现了 “Style editing for CSS-in-JS” 这项更新(如下图)。进入页面中看了看 —— Construct Stylesheets,CSS 还可以使用 JavaScript来构造?本文就来对 Construct Stylesheets 尝试这进行一番探索。

image

参考资料

https://github.com/WICG/construct-stylesheets/blob/gh-pages/explainer.md
https://developers.google.cn/web/updates/2019/02/constructable-stylesheets

快速Demo

// 1. 构造 CSSStyleSheet 实例
let sheet = new CSSStyleSheet;
// 2. 在该实例中插入一条CSS规则
sheet.insertRule(`body div{outline:1px solid #F00}`);
// 3. 将该实例包含的样式应用到 document
document.adoptedStyleSheets = [ sheet ]

以笔者写本文时使用的GitHub页面为例,下图中,左侧是页面原本的状态,右侧是执行以上代码后的状态。
image

@gogoend gogoend added 5% 写作进度 5% css dom TODO labels Sep 14, 2020
@gogoend
Copy link
Owner Author

gogoend commented Oct 24, 2021

const createStyleSheet = (rulesText) => {
let sheet = new CSSStyleSheet;
sheet.insertRule(rulesText);

return sheet
}
const injectStyleSheets = (document, ...styleSheets) => {
document.adoptedStyleSheets(styleSheets)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant