从现有 <div> and/or 获取背景图像 url 添加另一个属性到背景图像

Get the background-image url from an existing <div> and/or add another attribute to background-image

我正在尝试使用线性渐变更新现有背景图像。目前我的 CMS 正在创建背景图像,但我无法使用线性渐变更改不透明度。我只是想根据 CSS 使背景图像变暗。

我的解决方案 -> 从所有背景图片中获取 url div 类 (.bg-image) 以设置 "setAttribute" 新的背景图片标签.

   var elems = document.getElementsByClassName("bg-image");
    for (var i = 0, n = elems.length; i<n; ++i){
        var img = document.getElementsByClassName('bg-image')[i],
            bi = style.backgroundImage.slice(4, -1);

        img.setAttribute('style', 'background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),url("' bi +'"));');};

你将 jQuery 列为标签,所以我认为这是一个选项,尽管你使用的是原版:

$(".bg-image").each({
    $(this).css({
        backgroundImage:"inear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),"+$(this).css("backgroundImage"));
    });
});

没有jQuery解决办法:

如果你想要原版,你遇到的问题是 bi = style.backgroundImage.slice(4, -1); 应该是 bi = img.style.backgroundImage.slice(4, -1);

还有,不要这样设置样式

img.setAttribute('style', 'background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),url("' bi +'"));')

改为使用

img.style.backgroundImage="linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),url("+bi+")";

并且由于您无论如何都将其添加为 url,因此无需使用 slice 将其提取出来。此外,无需再次 select 元素。

var elems = document.getElementsByClassName("bg-image");
for (var i = 0; i<elems.length; i++){
    var bi = elems[i].style.backgroundImage;
    elems[i].style.backgroundImage="linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5),"+bi;
}

您不需要 javascript。这是一个 纯 CSS 解决方案:

原则是使用 :before 选择器并为其添加样式。

显然,一些细节会根据内容在背景样式 DOM 节点中的放置方式而有所不同,但如有必要,您可以使用 z-index 将内容放置在叠加层之上(或者,如果背景图像设置为css,您可以将其设置为#content:before,将rgba移动到#content,然后是z-index东西没关系)。

运行 下面的代码片段可以看到它的实际效果(我使用了红色调,所以你可以看到它不仅仅是一个黑暗的图像)。

#content {
  width: 400px;
  height: 200px;
  background: url("http://lorempixel.com/g/400/200/city/1/");
  position: relative;
  z-index: 1;
  color: white;
}
#content:before {
  content: "";
  position: absolute;
  z-index: 1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  /* you don't need a gradient with this method */
  background: rgba(255, 0, 0, 0.5);
}
<div id="content">
</div>