设置完“ var” css属性后,用JavaScript替换

我有一个设置了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替换已经设置的属性。这可能吗?

yan615 回答:设置完“ var” css属性后,用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',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',blue)');
}

function reset() {
  document.documentElement.style.setProperty('--b','initial');
}
.divwithbackground::after {
  content: "";
  display: block;
  height: 50px;
  background-image: var(--b,red);">
</div>

<button onclick="change()">change</button>
<button onclick="reset()">reset</button>

相关问题/答案以获取更多详细信息:

How to store inherit value inside a CSS custom property (aka CSS variables)?

CSS custom properties (variables) for box model

CSS scoped custom property ignored when used to calculate variable in outer scope

本文链接:https://www.f2er.com/2656105.html

大家都在问