javascript - 修改 :before style in Javascript. 上的背景(无库)

标签 javascript css

在我的应用程序中,我使用 :before 作为图像背景。这是为了“锐化”容器中的图像,因为它使用了 -webkit-filter: blur()

问题是我找不到使用 Javascript 更改 :before 样式的方法。我需要将背景图像更改为前景图像。

示例 CSS:

#image-container:before {
    background: url(img.png);
    content: '';
    position: fixed;
    z-index: -1;
    display: block;
    height: 40%;
}

#image-container {
    position: relative;
    width: 100%;
    height: 58%;
    overflow: hidden;
}

.blur {
    -webkit-filter: blur(10px);
}

在图像容器中我有以下代码:

<div id="image-container">
    <img class="blur" src="img.png" width="100%" height="100%">
</div>

问题是 img 源实际上来 self 的服务器,所以我需要背景与图像相匹配,这样边缘(来自模糊)看起来就不会草率和冲突。

所以这里的问题是,如何更改 #image-container:before CSS 样式的 background: url() 值?

没有图书馆。纯 Javascript。

最佳答案

试试下面的代码。供引用 -
http://davidwalsh.name/pseudo-element
http://pankajparashar.com/posts/modify-pseudo-elements-css/
你的css是这样的

#image-container:before {
   background: url(img.png);
   content: '';
   position: fixed;
   z-index: -1;
   display: block;
   height: 40%;
}

下面是获取后台的js

var color = window.getComputedStyle(
  document.querySelector('#image-container'), ':before'
).getPropertyValue('color')

并设置新的 css 属性

var style = document.createElement("style");

// Append the style tag to head
document.head.appendChild(style);

// Grab the stylesheet object
sheet = style.sheet

// Use addRule or insertRule to inject styles
sheet.addRule('#image-container::before','color: green');
sheet.insertRule('#image-container::before { color: green }', 0);

关于javascript - 修改 :before style in Javascript. 上的背景(无库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32839232/

相关文章:

javascript - jQuery 在倒数第四行之前添加行

css - Safari 中的动画剪辑路径不起作用

jQuery 循环 slider 问题

html - 我的 div 不会出现,但其他人会

javascript - 什么时候真正需要基于文件名的浏览器缓存清除?

javascript - 为什么我的 JSON 返回单引号(撇号)的转义码

CSS - 将图像定位到左侧 + 部分剪切 + 响应式 + Bootstrap

html - HTML、正文和 div 有问题

javascript - 颜色图在 100% 的情况下不起作用

javascript - 从表单在同一页面内调用 JS 函数(AJAX)