在我的应用程序中,我使用 :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/