Is it possible in Javascript to add a style property twice to an element?

Given the HTML Element object, is it possible to add the same style property twice to it without resorting to string manipulation?

Consider the following examples:

<div style="width: 90%; width: calc(100% - 5em);"></div>
<h1 style="font-weight: bold; font-weight: 800;"></h1>
<p style="color: #cccccc; color: rgba(255, 255, 255, 0.8);"></p>

As far as I can tell, setting styles through a property .style(e.g. element.style.color = "blue") or .style.setProperty(e.g. element.style.setProperty("color", "blue")) overwrites existing style properties rather than adding them.

Having multiple definitions of the same property allows us to use the cascading nature of CSS, allowing us to use more modern CSS property values ​​when available, with a graceful return to “good enough” values ​​where more recent additions are not supported. However, the only way I can do something like this is by manually manipulating the string.

+4
source share
2 answers

What you want to do is not possible if you are not using any javascript custom function.

I assume this is due to how CSS specificity works .

- , , CSS , , . , , CSS, . , . : https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

, property style, - . "" Javascript .style.setProperty("propertyName", "propertyValue") element.style.propertyName = "propertyValue". , , .

+2

, . ( , ).

, , , CSS.
- <style> .
document.styleSheets.

.

  • -, , , element.setAttribute('style', 'prop1: val1; prop1:val2; prop1:val3').
    , , .

  • -, style js , CSS.

document.body.style.backgroundImage = 'url("http://fakeserver.com/myGradientFallback.png")';
document.body.style.backgroundImage = 'linear-gradient(to right, #499bea 0%,#ff51fc 53%,#207ce5 100%)';
document.body.style.backgroundImage = 'awesome-property-that-your-browser-doesnt-support-yet(100%)';
Hide result

, , , CSS, js-.

+1

Source: https://habr.com/ru/post/1658185/


All Articles