如何使用https加载页面时从CSS调用图像

时间:2009-12-23 15:35:06

标签: css internet-explorer

这个让我疯了。它(还)是另一个IE6 / 7特性,但我的一个网页需要使用https加载。在IE6 / 7中,我得到了可怕的“包含安全和不安全的项目”消息,这会导致用户恐慌。我已经完成了从上到下的代码,并将问题(如IE所见)与我的CSS中的背景图像隔离开来。但是,这些使用绝对路径......

background: url(/images/imagename.jpg);

看起来这会绊倒IE并导致https上的不安全消息。任何人有任何想法如何解决这个问题?任何帮助非常感谢。

4 个答案:

答案 0 :(得分:2)

这不应该给你带来任何麻烦,只要CSS文件本身也来自HTTPS。没有显式协议的绝对路径(即/path/to/file而不是http://example.com/path/to/file)继承了调用它们的文件的协议,无论是HTML还是CSS。

我们可以看到您的信息页吗?您可能会忽略页面上的其他内容。

答案 1 :(得分:1)

你是对的,背景风格的相对网址路径会导致此消息出现在IE6 / 7中。

我成功使用的唯一方法是从可用的浏览器数据构建绝对路径,或者对绝对路径进行硬编码。以下是如何使用JavaScript构建绝对路径的示例:

使用这样的顶级样式定义:

<style type="text/css">
    .fixBgImage {
        background: url(/images/imagename.jpg);
    }
</style>

您可以使用查找该规则的JavaScript函数,并更改该规则的backgroundImage样式。 (请记住,此示例假定您已在工作表[0]上定义规则)

        // this function needs to be run after the page has loaded
        // (body.onload, window.onload or something similar)
        function fixBackgroundImages() {
            // using sheet 0 defined first on this page
            var rule = getRule('.fixBgImage', document.styleSheets[0]);         
            if (rule != null) {
                var bgUrl = rule.style.backgroundImage.replace(/^url|[\(\)]/g, '');
                bgUrl = fixHttpsBgUrl(bgUrl);
                rule.style.backgroundImage = 'url("' + bgUrl + '")';
            }
        }

        function getRule(name, sheet){
            var rules = (sheet.rules) ? sheet.rules : sheet.cssRules;

            for (var i = 0; i < rules.length; i++) {
                if (rules[i] && rules[i].selectorText == name) {
                    return rules[i];
                }
            }

            return null;    
        }

       // This function returns an absolute path if https is used
       function fixHttpsBgUrl(imgUrl){
          if (document.location.protocol.indexOf('https') >= 0){
            var basepath = document.URL.substring(0, document.URL.lastIndexOf('/') + 1);
            var pcol = document.location.protocol + '//';
            var host = document.location.hostname;
            var port = (document.location.port) ? ':' + document.location.port : '';

            if (imgUrl.indexOf('/') == 0){ // server root path
              imgUrl = pcol + host + port + imgUrl;
            }
            else{  // app root
              imgUrl = basepath + imgUrl;
            }
          }
        }

答案 2 :(得分:0)

尝试:

background: url(//images/imagename.jpg);

根据应该有效的this answer。尝试将它用于样式表,例如:

<link rel="stylesheet" type="text/css" src="//style/style.css" />

答案 3 :(得分:0)

只要相对于安全的根目录,IE对于相对映像图像应该完全没有问题。你很可能遇到的问题是在其他地方造成的。

http://blogs.msdn.com/ieinternals/archive/2009/06/22/HTTPS-Mixed-Content-in-IE8.aspx