Replace with Javascript the 'var' css property after it has been already set

不羁的心 提交于 2021-01-27 19:50:55

问题


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;
 }

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');

this way. Well this works if I remove style this from the DIV tag:

 style="--page-header-section-background: url('myurlimage.jpg');

But this is not the behavior I want. I would like javascript to replace the already set property. Is this possible ?


回答1:


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:

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://stackoverflow.com/questions/60659642/replace-with-javascript-the-var-css-property-after-it-has-been-already-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!