【问题标题】:External CSS styles cant be accessed in Google Chrome无法在 Google Chrome 中访问外部 CSS 样式
【发布时间】:2014-08-19 18:36:43
【问题描述】:

所以我有以下代码

<html>
<head>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
        document.styleSheets[0].cssRules[0].style.color="blue";
    </script>
</head>
//etc.

所以基本上这段代码在 IE 和 Mozilla 中有效,但在 Chrome 中无效。实际上,当您运行 document.styleSheets[0].cssRules 时,它会返回一个 CSSRulesList 对象(在 IE 和 Mozilla 中),但在 Chrome 中它会返回 null。顺便说一句,对于嵌入式样式,这个对象似乎甚至在 Chrome 中也可以工作。

那么这个功能实际上在 Chrome 中不可用吗?如果是这样,是否有 Chrome 替代方案可以让您使用 Javascript 处理外部样式表/文件?

【问题讨论】:

    标签: javascript css google-chrome stylesheet external


    【解决方案1】:

    另一种选择

    document.styleSheets[0].rules[0].style.color = "blue";
    

    这个 sn-p 可能有助于查看支持的集合。建议先使用cssRules 集合,如果不支持,则使用rules 集合。

    if (document.styleSheets[0].cssRules)
        document.styleSheets[0].cssRules[0].style.color = "blue";
    else if (document.styleSheets[0].rules)
        document.styleSheets[0].rules[0].style.color = "blue";
    

    编辑

    下面的 sn-p 在 IE8、IE11、Firefox、Chrome、Safari 和 Opera 上按预期工作;在我的本地和生产服务器上;它也适用于jsbin;但它不适用于 jsfiddle - 在上述任何浏览器上!

    <!DOCTYPE>
    <html>
    <head>
    <style type="text/css">
        .panel { 
            background-color: #00ff00; 
            color: #ffffff; 
            width: 100px; 
            height: 100px; 
            font-size: 30px;
        }
    </style>
    <script type="text/javascript">
    window.onload = function(){
        document.getElementById('button').onclick = function() {
            if (document.styleSheets[0].cssRules)
                document.styleSheets[0].cssRules[0].style.color = "black"; 
            else if (document.styleSheets[0].rules)
                document.styleSheets[0].rules[0].style.color = "black";
        };
    };
    </script>
    </head>
    <body>
        <div class="panel"><b>Text</b></div>
        <input type="button" name="button" id="button" value="Change Color" />
    </body>
    </html>
    

    如果我将 style 部分更改为此

    <link rel="stylesheet" type="text/css" href="http://external-server/styles.css" />
    

    上面的 sn-p 只适用于 IE11。所以,它似乎是 cross-domain policy issue,因为 Firefox 说的是 The Same Origin Policy disallows reading the remote resource at http://external-server/styles.css. This can be fixed by moving the resource to the same domain or enabling CORS.

    也许下面的sn-p可以解决问题

    <style type="text/css">
        @import url("http://external-domain/styles.css");
    </style> 
    

    好吧,@import tip 失败了!但是让我们检查从外部服务器收到的标头

    Remote Address: x.x.x.x:x
    Request URL: http://www.external-domain.com/styles.css
    Request Method: GET
    Status Code: 200 OK
    +[Request Headers] 10
    -[Response Headers] 11
      Accept-Ranges: bytes
      Connection: Keep-Alive
      Content-Encoding: gzip
      Content-Length: 105
      Content-Type: text/css
      ...
    

    如我们所见,我们拥有样式,但无法访问或更改它们。 Chrome 和 Opera 都在说

    `Uncaught TypeError: Cannot set property 'color' of undefined`;
    

    Firefox 也这么说,但更详细

    `TypeError: document.styleSheets[0].cssRules[0].style is undefined` 
    

    最后,即使是 IE11 也有同样的看法 :)

    `SCRIPT5007: Unable to set property 'color' of undefined or null reference. 
    File: css.html, Line: 30, Column: 4`   
    

    好吧,此时还有一件事要考虑 - CORS 请求?! IE 8+、Firefox 3.5+、Chrome 3+、Opera 12+、Safari 4+ 支持 CORS ...

    使用 CORS 访问托管在外部域上的 CSS

    <!DOCTYPE>
    <html>
    <head>
    <meta charset="utf-8">
    <script type="text/javascript">
    // Access CSS hosted on external domain using CORS
    // http://stackoverflow.com/users/1310701/hex494d49
    //
    window.onload = function(){
        var xhr = CORSRequest("GET", "http://external-domain/styles.css");
        if (!xhr){ // if CORS isn't supported
            alert("Still using Lynx?");
            return;
        }
        xhr.onload = function() {
            var response = xhr.responseText;
            appendCSS(response);
        }
        xhr.onerror = function() {
            alert('Something went wrong!');
        };
        xhr.send();
    
        document.getElementById('button').onclick = function() {
            if (document.styleSheets[0].cssRules)
                document.styleSheets[0].cssRules[0].style.color = "black"; 
            else if (document.styleSheets[0].rules)
                document.styleSheets[0].rules[0].style.color = "black";
        };
    };
    
    var appendCSS = function(css){
        var s = document.createElement('STYLE');
        s.setAttribute('type', 'text/css');
        if(s.styleSheet)  // IE
            s.styleSheet.cssText = css;
        else  // the rest of the world
            s.appendChild(document.createTextNode(css));
        document.getElementsByTagName('HEAD')[0].appendChild(s);
    };
    
    var CORSRequest = function(method, url){
        var xhr = new XMLHttpRequest();
        if("withCredentials" in xhr){  // Chrome, Firefox, Opera, Safari
            xhr.open(method, url, true);
        }else if(typeof XDomainRequest != "undefined"){  // IE
            xhr = new XDomainRequest();
            xhr.open(method, url);
        }else{ // CORS isn't supported
            xhr = null;
        }
        return xhr;
    };
    
    </script>
    </head>
    <body>
        <div class="panel"><b>Text</b></div>
        <input type="button" name="button" id="button" value="Change Color" />
    </body>
    </html>
    

    就是这样,它有效!刚刚在 IE8、IE11、Firefox、Chrome、Opera 和 Safari 上进行了测试。但是......只有在网络服务器上启用了Access-Control-Allow-Origin,否则你会得到这样的错误

    XMLHttpRequest cannot load http://external-domain/styles.css. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

    在我的服务器上它没有启用,所以我必须自己做。如果使用共享主机,这可能是个问题。

    Off-topic: 如何在 Apache 上启用 Access-Control-Allow-Origin

    首先,启用 Apache Headers 模块

    ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load
    

    重启 Apache

    /etc/init.d/apache2 restart
    

    在 Apache 配置文件的 Directory 部分下添加这些行

    Header add Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
    

    或将它们添加到 .htaccess 文件中。最后两个可以省略。如果您想限制只有某个人可以访问,请将上一行中的“*”替换为“www.my-kitchen.com”。再次重启网络服务器,就是这样。

    【讨论】:

    • 啊忘了提,但这不是问题。 “规则”和“cssRules”在 Chrome 中都不起作用;两者都返回 null。
    • @user3398216 您尝试访问的样式是否托管在外部域上?无论如何,检查更新的答案,同时我会做更多的测试。
    猜你喜欢
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多