【问题标题】:How to assign background-image url dynamically with only html and css? [duplicate]如何仅使用 html 和 css 动态分配背景图像 url? [复制]
【发布时间】:2019-12-08 13:15:16
【问题描述】:

我正在尝试通过 html 标签上定义的属性中的 css 动态分配 background-imageurl。但似乎attr()var() 都不起作用。我避免使用 javascript,因为 url 稍后可能会更改,所以我必须再次手动触发该脚本。

有没有更好的解决方案?

body {
  display: flex;
}

.normal, .attr, .var {
  flex: 1;
  height: 240px;
  border: solid 1px #666;
  background-size: cover;
}

.normal {
  background-image: url("https://picsum.photos/320/240");
}

.attr {
  background-image: url(attr(data-bg));
}

.var {
  background-image: url(var(--url));
}
<div class="normal"></div>
<div class="attr" data-bg="https://picsum.photos/320/240"></div>
<div class="var" style="--url: 'https://picsum.photos/320/240';"></div>

如果可能的话,我希望我可以连接字符串。

.image {
  border: solid 1px #666;
  width: 320px;
  height: 240px;
  /* I wish this is possible */
  background-image: url("http://www.example.com/images/" attr(data-bg) ".png");
}
&lt;div class="image" data-bg="adorable_cat"&gt;&lt;/div&gt;

【问题讨论】:

    标签: html css css-variables


    【解决方案1】:

    即使我觉得简单地使用内联 background-image 属性会更容易(特别是如果你想连接 url 字符串)。为了简单的使用,你可以这样做:

    <div class="var" style="--url: url(https://picsum.photos/320/240)"></div>
    
    .var {
      background-image: var(--url);
    }
    

    由于我不清楚的原因,使用 url(var(--url)); 似乎根本不起作用(至少在 Chrome 中)

    【讨论】:

    【解决方案2】:

    将嵌入的样式表放入文档的:

    <style type="text/css">
    .logo
    {
    background: #FFF url(<?php echo $variable_holding_img_url; ?>);
    }
    </style>
    

    更多信息

    enter link description here

    How to have dynamic image as CSS background?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 2014-10-20
      • 2015-05-06
      • 2019-04-22
      相关资源
      最近更新 更多