我有一个元素,其上设置了 var 属性,如下所示:
<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 该怎么办:
document.documentElement.style.setProperty('--page-header-section-background', bgDataValue, 'important');
这边走。好吧,如果我从 DIV 标签中删除此样式,这会起作用:
style="--page-header-section-background: url('myurlimage.jpg');
但这不是我想要的行为。我想要 javascript 来替换已经设置的属性。这可能吗 ?
您需要以元素本身为目标来覆盖变量
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>
或者,如果您想定位根元素,请考虑后备技巧:
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>
您还可以根据需要设置/重置初始值:
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>
有关更多详细信息的相关问题/答案:
如何在 CSS 自定义属性(又名 CSS 变量)中存储继承值? https://stackoverflow.com/q/53239880/8620333
盒模型的 CSS 自定义属性(变量) https://stackoverflow.com/q/55615332/8620333
CSS 作用域自定义属性在用于计算外部作用域中的变量时被忽略 https://stackoverflow.com/q/52015737/8620333
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)