问题描述
我有一个设置了var属性的元素,如下所示:
I've an element with a var property set on it like so:
<div class="divwithbackground" style="--page-header-section-background: url('myurlimage.jpg');">
</div>
CSS
.divwithbackground::after {
background-image: var(--page-header-section-background);
background-position: center;
background-size: cover;
}
这实际上很好.但是,如果我还有另一个设置属性的javascript会怎么办:
This actually works well. But what if I have another javascript which sets the property:
document.documentElement.style.setProperty('--page-header-section-background', bgDataValue, 'important');
这样.好吧,如果我从DIV标签中删除了样式,这会起作用:
this way. Well this works if I remove style this from the DIV tag:
style="--page-header-section-background: url('myurlimage.jpg');
但这不是我想要的行为.我想用javascript替换已经设置的属性.这可能吗?
But this is not the behavior I want. I would like javascript to replace the already set property. Is this possible ?
推荐答案
您需要定位元素本身以覆盖变量
You need to either target the element itself to override the variable
setTimeout(function() {
document.querySelector('.divwithbackground').style.setProperty('--b', 'linear-gradient(blue,blue)');
},1500);
.divwithbackground::after {
content: "";
display: block;
height: 50px;
background-image: var(--b);
}
<div class="divwithbackground" style="--b: linear-gradient(red,red);">
</div>
或者,如果要定位根元素,可以考虑使用一个备用技巧:
Or consider a fallback trick if you want to target the root element:
setTimeout(function() {
document.documentElement.style.setProperty('--b', 'linear-gradient(blue,blue)');
},1500);
.divwithbackground::after {
content: "";
display: block;
height: 50px;
background-image: var(--b,var(--c));
}
<div class="divwithbackground" style="--c: linear-gradient(red,red);">
</div>
您还可以根据需要设置/重置初始值:
You can also set/reset the initial value like you want:
function change() {
document.documentElement.style.setProperty('--b', 'linear-gradient(blue,blue)');
}
function reset() {
document.documentElement.style.setProperty('--b', 'initial');
}
.divwithbackground::after {
content: "";
display: block;
height: 50px;
background-image: var(--b, var(--c));
}
<div class="divwithbackground" style="--c: linear-gradient(red,red);">
</div>
<button onclick="change()">change</button>
<button onclick="reset()">reset</button>
相关问题/答案以获取更多详细信息:
Related questions/answers for more details:
这篇关于设置完后,用Javascript替换"var" css属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!