简体   繁体   中英

Why Chrome cannot access to external stylesheet using insertRule with Javascript?

I have a HTML file, and linked in the head, an external stylesheet, and both of them are in the same folder. There are only one stylesheet. In the bottom of the body, i have a script:

document.styleSheets[0].insertRule(".example{position: relative}", 0);

But i get this error message (suprisingly only on Chrome 64, on FireFox, Safari mobile and Chrome mobile works well):

Uncaught DOMException: Failed to execute 'insertRule' on 'CSSStyleSheet': Cannot access StyleSheet to insertRule

Why?

Change the index for your insert. In CSS files all @ Rules must be at the top of the file. So, if you have 4 @ rules at the top of the CSS file, change the index to 4 thus:

document.styleSheets[0].insertRule(".example{position: relative}", 4);

That should work.

Here is the spec reference (see the note):

https://drafts.csswg.org/cssom/#insert-a-css-rule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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