我知道document.styleSheets
,它由页面中所有有效的样式表组成。我想知道我是否可以创建一个新的,并通过javascript将其附加到present list中。
我试过document.styleSheets[0].constructor
,document.styleSheets[0].__proto__.constructor
,new CSSStyleSheet
,CSSStyleSheet()
,我从Chrome上得到的都是TypeError: Illegal constructor
。CSSStyleSheet.constructor()
返回了一个纯对象,可我需要一个CSSStyleSheet对象。
我知道我可以创建一个链接/样式元素并附加它,然后修改它。我想知道的是,我能用javascript直接创建这样的对象吗?
发布于 2014-06-18 20:44:11
我知道你说你不想创建一个元素,但这是真正做到这一点的唯一方法。上面有一些人详细介绍了这种方法,但我注意到没有人提到HTMLStyleElement
和HTMLLinkElement
都有一个整洁的sheet
property来直接访问他们的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);
比通过document.styleSheets
搜索简单得多
发布于 2019-01-13 02:27:32
有了a brand new proposal,就可以直接调用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];
请注意,目前这只适用于Chrome Canary,但希望其他浏览器很快就能实现这一功能。
发布于 2011-11-21 16:41:44
如果您尝试在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);
https://stackoverflow.com/questions/8209086
复制相似问题