【问题标题】:Use data attribute to set the background image of a pseudo element [duplicate]使用数据属性设置伪元素的背景图像[重复]
【发布时间】:2015-08-23 03:13:26
【问题描述】:

有没有方便的方法通过数据属性设置伪元素的背景图片?

我正在尝试实现这样的目标,但我希望能够通过我的 CMS 在标记中设置背景图像:

.full-width {
  background-color: #ededed;
  width: 100%;
  position: relative;
  z-index: -1;
}
.full-width:after {
  content: '';
  display: block;
  position: absolute;
  width: 50%;
  height: 100%;
  left: 50%;
  top: 0;
  background-image: url(//unsplash.it/1080/1920);
  background-size: cover;
  background-position: left center;
  z-index: -1;
}
.full-width .container {
  z-index: 99;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="full-width">
  <div class="container">
    <div class="row">
      <div class="col-xs-6">
        <h2>Test 123</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
      </div>
    </div>
  </div>
</div>

不是How can I use a data attribute to set a background-image in CSS? 的直接复制品,因为我说的是伪元素。感谢您将我与此联系起来,但我已经知道这些技术。

【问题讨论】:

  • 所有重复标记是怎么回事?这显然不是 那个 类似于他们链接到的。 :?

标签: html css pseudo-element custom-data-attribute


【解决方案1】:

根据 CSS attr 函数的 compatibility table,您只能在 content 规则中使用 attr 返回的值(如果您想要任何形式的跨浏览器支持)。

因此,如果您想实现类似于您希望的功能,则需要使用 JavaScript,因为 attr 不能在 background 中使用。

【讨论】:

    【解决方案2】:

    目前,这是不可能的。未来,希望。使用attr() 函数,可以从元素中获取属性值。使用伪元素时,它从原始元素中获取属性。因此,您可以通过background-image: attr('data-bg' 'url') 获取data-bg 属性并将其视为URL。

    很遗憾,目前尚不支持任何浏览器,并且仍是规范的实验性(可能会被删除)部分。

    .full-width {
      background-color: #ededed;
      width: 100%;
      position: relative;
      z-index: -1;
    }
    .full-width:after {
      content: '';
      display: block;
      position: absolute;
      width: 50%;
      height: 100%;
      left: 50%;
      top: 0;
      background-image: attr('data-bg' 'url');
      background-size: cover;
      background-position: left center;
      z-index: -1;
    }
    .full-width .container {
      z-index: 99;
    }
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
    <div class="full-width" data-bg="//unsplash.it/1080/1920">
      <div class="container">
        <div class="row">
          <div class="col-xs-6">
            <h2>Test 123</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
          </div>
        </div>
      </div>
    </div>

    【讨论】:

    • 哇,我刚得到忍者。
    • 我会赞成你的两个答案;)
    • 不显示图片
    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多