简体   繁体   中英

document.styleSheets[i].disabled doesn't work in chrome

I have a pretty weird problem to solve; the solution should be pure JavaScript (no frameworks allowed). Here it is: "display all stylesheets that are enabled on the page".

I use chrome because of multiple issues of innerHtml in IE, although it has cssText property of a stylesheet, which suits perfectly for my purpose.

Anyway, here is my example

<html>
    <head>
        <style MEDIA="screen">
            h1 {color:blue; font-size:10pt; background-color:cyan}
        </style>
        <style MEDIA="screen" DISABLED="true">
            h4 {color:blue; font-size:10pt; background-color:cyan}
        </style>
        <style MEDIA="print">
            h1 {color:gray; font-size:12pt; font-weight: bold}
            h2 {font-style:italic}
        </style>
        <style DISABLED="true">
            h2 {color:green; font-size:12pt}
        </style>
        <style>
            h3 {font-style:italic}
        </style>

        <script language="Javascript">
            function displayActiveStyles() {
                var container = document.getElementById('activeStyles');                                
                var i;
                for (i=0; i<document.styleSheets.length; i++) {
                    alert(document.styleSheets[i].disabled);
                }   
            }                  
        </script>
    </head>
    <body>
        <h1>one</h1>
        <h2>two</h2>
        <h3>three</h3>
        <input type="button" value="show" onclick="displayActiveStyles()" >
        <hr />
        <div id="activeStyles"></div>
    </body>
</html>

The problem is, for all 5 stylesheets it alerts false which isn't right. If anybody has any ideas of where I am making a mistake or if it is doable in chrome at all, please let me know.

I understand that you want to list the href's of each stylesheet, right? In your code, you're going through each stylesheet, and alerting it's disabled property. Since they're enabled, they are alerting "false", which is correct. If you want to get the href of only the enabled ones, you could do something like:

var i;
for (i = 0; i < document.styleSheets.length; i++) {
    if (!document.styleSheets[i].disabled) {
        alert(document.styleSheets[i].href);
    }
}

Trying this here, there's one styleSheet for which its href is null . Not really sure why's that, I googled something quickly and it's probably because it is a <style> tag. You can add a check for document.styleSheets[i].href along with the check for disabled`.

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