我可以动态创建 CSSStyleSheet 对象并插入它吗?

发布于 2024-12-17 07:59:28 字数 492 浏览 2 评论 0 原文

我知道 document.styleSheets 它由页面中的所有有效样式表组成。我想知道是否可以创建一个新列表并通过 JavaScript 将其附加到当前列表中。

我尝试过 document.styleSheets[0].constructordocument.styleSheets[0].__proto__.constructornew CSSStyleSheet CSSStyleSheet(),我从 Chrome 得到的只是:

类型错误:非法构造函数。

CSSStyleSheet.constructor() 返回一个纯对象,但我期望一个 CSSStyleSheet 对象。

我知道我可以创建一个链接/样式元素并附加它,然后修改它。我可以直接用 JavaScript 创建这样的对象吗?

I know document.styleSheets which consists of all valid style sheets in a page. I want to know whether I can create a new one and append it to present list via JavaScript.

I have tried document.styleSheets[0].constructor, document.styleSheets[0].__proto__.constructor, new CSSStyleSheet, CSSStyleSheet(), and all I get from Chrome is:

TypeError: Illegal constructor.

CSSStyleSheet.constructor() returned a pure object but I expect a CSSStyleSheet object.

I know I can create a link/style element and append it, then modify it. Can I create such objects directly with JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

旧伤还要旧人安 2024-12-24 07:59:28

一项提案可以直接调用CSSStyleSheet构造函数。做你想做的事情看起来像这样:

// Construct the CSSStyleSheet
const stylesheet = new CSSStyleSheet();

// Add some CSS
stylesheet.replaceSync('body { background: #000 !important; }')
// OR stylesheet.replace, which returns a Promise instead

// Tell the document to adopt your new stylesheet.
// Note that this also works with Shadow Roots.
document.adoptedStyleSheets = [stylesheet];

There's a proposal that makes it possible to directly call the CSSStyleSheet constructor. Doing what you want to looks like this:

// Construct the CSSStyleSheet
const stylesheet = new CSSStyleSheet();

// Add some CSS
stylesheet.replaceSync('body { background: #000 !important; }')
// OR stylesheet.replace, which returns a Promise instead

// Tell the document to adopt your new stylesheet.
// Note that this also works with Shadow Roots.
document.adoptedStyleSheets = [stylesheet];
难忘№最初的完美 2024-12-24 07:59:28

我知道您说过您不想创建一个元素,但这确实是唯一的方法。上面有一些人详细介绍了这种方法,但我注意到没有人掩盖 HTMLStyleElementHTMLLinkElement 都有一个简洁的 sheet 属性 来直接访问其 CSSStyleSheet

var style = document.createElement("style");
document.head.appendChild(style); // must append before you can access sheet property
var sheet = style.sheet;

console.log(sheet instanceof CSSStyleSheet);

更简单比搜索文档.styleSheets

I know you said you didn't want to create an element, but that's genuinely the only way to do it. A few people have detailed this approach above, but i notice nobody covered off that HTMLStyleElement and HTMLLinkElement both have a neat sheet property to get direct access to their CSSStyleSheet:

var style = document.createElement("style");
document.head.appendChild(style); // must append before you can access sheet property
var sheet = style.sheet;

console.log(sheet instanceof CSSStyleSheet);

Much simpler than searching through document.styleSheets

无边思念无边月 2024-12-24 07:59:28

如果您尝试在 javascript 中编写 css,请执行以下操作:

var s = document.createElement('style');
s.type = 'text/css';
s.innerText = 'body { background: #222; } /*... more css ..*/';
document.head.appendChild(s);

而如果您尝试从服务器加载样式表:

var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = '/url/to/css/file.css';
document.head.appendChild(s);

If you are trying to write the css inside of javascript, do this:

var s = document.createElement('style');
s.type = 'text/css';
s.innerText = 'body { background: #222; } /*... more css ..*/';
document.head.appendChild(s);

Whereas if you are trying to load a stylesheet from the server:

var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = '/url/to/css/file.css';
document.head.appendChild(s);
江挽川 2024-12-24 07:59:28

是的,你可以。 document.styleSheets 不能直接修改,但您可以通过向文档中添加新的样式标签来添加条目:

// Create the style element
var elem = $('<style id="lwuiStyle"></style>');
$('head').append(elem);

// Find its CSSStyleSheet entry in document.styleSheets
var yourSheet = null;
for (var sheet of document.styleSheets) {
    if (sheet.ownerNode == elem[0]) {
        yourSheet = sheet;
        break;
    }
}

// Test it by changing the background colour
yourSheet.insertRule('body {background-color: #fa0}', yourSheet.cssRules.length);

如果您运行 Firefox,则可以直接在 Scratchpad 中进行测试:复制代码,按Shift+F4,粘贴它,然后使用 Ctrl+L 运行代码。玩得开心!

Yes, you can. The document.styleSheets cannot be modified directly, but you can add an entry by adding a new style tag to your document:

// Create the style element
var elem = $('<style id="lwuiStyle"></style>');
$('head').append(elem);

// Find its CSSStyleSheet entry in document.styleSheets
var yourSheet = null;
for (var sheet of document.styleSheets) {
    if (sheet.ownerNode == elem[0]) {
        yourSheet = sheet;
        break;
    }
}

// Test it by changing the background colour
yourSheet.insertRule('body {background-color: #fa0}', yourSheet.cssRules.length);

If you run Firefox, you can directly test this in Scratchpad: Copy the code, press Shift+F4, paste it, and run the code with Ctrl+L. Have fun!

玉环 2024-12-24 07:59:28

据我所知,唯一接近您要求的方法是仅限 IE document.createStyleSheet([url] [,index]) 方法,您可以使用它创建最多 31 个* styleSheet 对象(之后您仍然需要手动创建 style 元素并将它们附加到 document< /代码>)。

此答案展示了如何定义用于非 IE 浏览器的 createStyleSheet() 方法,但正如您所期望的那样,它是通过附加 link/style 元素(出于某种原因)来实现的你试图避免)。


* IE 6 至 9 仅限于 31 个导入样式表由于用于存储工作表的 5 位字段ID。在 IE10 中,此限制已提高到 4095。

As far as I know, the only approach that comes close to what you're asking for is the IE-only document.createStyleSheet([url] [,index]) method which you can use to create up to 31* styleSheet objects (after which you'll still need to manually create style elements and append them to document).

This answer shows how you can define the createStyleSheet() method for non-IE browsers but as you'd expect it does so by appending link/style elements (which for some reason you're trying to avoid).


* IE 6 to 9 is limited to 31 imported stylesheets due to 5-bit field used for storing sheet IDs. In IE10 this limit has been raised to 4095.

东京女 2024-12-24 07:59:28

你尝试过这个吗:

var myCSSStyleSheetIbj = Object.create(document.styleSheets[0])

假设 document.styleSheets[0] 是一个 CSSStyleSheet 对象,
实际上,如果你用任何 CSSStyleSheet 替换 document.styleSheets[0] 就可以了。

Did you try this:

var myCSSStyleSheetIbj = Object.create(document.styleSheets[0])

Assuming that document.styleSheets[0] is a CSSStyleSheet Object,
Actually if you replace document.styleSheets[0] with any CSSStyleSheet it would work.

那小子欠揍 2024-12-24 07:59:28

Object.create(CSSStyleSheet.prototype)

返回 CSSStyleSheet 的空实例。换句话说,它的作用正是您所期望的 new CSSStyleSheet 的作用。

Object.create 可在任何支持 ECMAScript 5 的浏览器中使用。在此处查找兼容性表。

Object.create(CSSStyleSheet.prototype)

gives you back an empty instance of CSSStyleSheet. In other words, it does exactly what you would expect new CSSStyleSheet to do.

Object.create is available in any browser with ECMAScript 5 support. Find a compatibility table here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文