【问题标题】:Dynamically loaded CSS background-image not shown in Chrome动态加载的 CSS 背景图像未在 Chrome 中显示
【发布时间】:2014-07-24 04:23:55
【问题描述】:

我正在为组织制作一个 github gist 画廊,您可以在 elsherbini.github.io/gist-gallery 看到它。

缩略图通过javascript放置在页面上,背景图片设置为内联样式规则。在 Firefox 和 Internet Explorer 中显示背景图像,而在 Chrome 和 Safari 中则不显示。

在Firefox中,以下代码返回背景图片的正确url,而在chrome中返回"none"

$($(".thumbnail")[0]).css("background-image")

因此我无法使用the following fix by andrew cantino

function refreshBackgrounds(selector) {
  // Chrome shim to fix http://groups.google.com/a/chromium.org/group/chromium-bugs/browse_thread/thread/1b6a86d6d4cb8b04/739e937fa945a921
  // Remove this once Chrome fixes its bug.
  if (/chrome/.test(navigator.userAgent.toLowerCase())) {
    $(selector).each(function() {
      var $this = $(this);
      if ($this.css("background-image")) {
        var oldBackgroundImage = $this.css("background-image");
        setTimeout(function() {
          $this.css("background-image", oldBackgroundImage);
        }, 1);
      }
    });
  }
}

当其他人出现类似问题时,我已经尝试在 URL 中添加单引号,正如一些人所建议的那样。如果我查看网络选项卡,它甚至不会请求图像。如果我在 chrome devtools 中手动将背景图像属性设置为新规则,它可以工作,所以我知道这不是 url 格式或愚蠢的语法错误的问题。

chrome 中的这个错误有解决方法吗?

【问题讨论】:

  • 我可能错了,但我认为$this$(this) 的内存副本,不会影响DOM。尝试在代码中将$this 替换为$(this)
  • $this 仍然是指 DOM 节点,它只是避免让 jQuery 每次查找它。我尝试更改它,但没有解决问题。
  • 哦,值得一试,我猜 XD

标签: javascript jquery html css google-chrome


【解决方案1】:

另外(或者更确切地说),在我的浏览器中,由于缺少 url() 声明的右括号,因此无法正确解析背景图像样式。修复它,然后可以使用 $().css() 检索背景图像。

详情:我明白了

 <a style="background-image: url(https://../thumbnail.png" class="gist thumbnail" href="..">

应该是

 <a style="background-image: url(//../thumbnail.png)" class="gist thumbnail" href="..">

【讨论】:

  • 这就是问题所在。无论如何,firefox 和 IE 似乎解析了错误的 css,但由于我的下划线模板存在问题,Chrome 放弃了该规则。谢谢。
【解决方案2】:

$this.css("background-image", oldBackgroundImage); 更改为$this.css('background-image', 'url(' + oldBackgroundImage + ')');

【讨论】:

  • 这并不能解决问题。在 firefox oldBackgroundImage === "url("https://gist.githubusercontent.com/elsherbini/13383ffc376b54ad34ea/raw/55fbdfcf4d76dde2e6e3d1b638aacd47cd3aed33/thumbnail.png")" 中(它已经有 url() 部分)。在 Chrome 中,oldBackgroundImage === "none"
  • 我了解到它目前在 Firefox 中有效。不是这样吗?
  • 是的,它可以在 Firefox 中使用。只是为了确保代码在我在 firefox 中运行(没有测试用户代理)并正确重置背景图像时正常工作。如果您愿意,可以自己尝试,链接在问题的顶部。
猜你喜欢
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
  • 2015-06-27
  • 1970-01-01
  • 2015-07-10
相关资源
最近更新 更多