简体   繁体   中英

Accessing CSS stylesheet's rules without adding stylesheet to the head

I have loaded a stylesheet with AJAX, the file is stored in the data variable. Now I need to access it's rules (there's a functionality behind it). The solution I am using now is this:

stylesheet = document.createElement('style');
stylesheet.type = 'text/css';
stylesheet.innerHTML = data;

document.head.appendChild(stylesheet);
stylesheet = document.styleSheets[2]; // I know which one is my file

rules = stylesheet.rules || stylesheet.cssRules;

Now the problem is that when it is added to the head, styling is applied on the page. How do I do the same without adding to the head?

Tried various things with Object.create(CSSStyleSheet.prototype) but couldn't get it done...

I would simply create an empty hidden iframe and append stylesheet there. This way it would not affect anything and you would still be able to read its cssRules.

For example:

stylesheet = document.createElement('style');
stylesheet.type = 'text/css';
stylesheet.innerHTML = data;

var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);

var iframeDoc = iframe.contentWindow.document || iframe.contentDocument;
iframeDoc.body.appendChild(stylesheet);

stylesheet = iframeDoc.styleSheets[0];
rules = stylesheet.rules || stylesheet.cssRules;

Demo: http://plnkr.co/edit/hlNlpzfRmLP8IYYwePeC?p=preview

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