简体   繁体   中英

Using element's attribute value as a selector in CSS

I've been trying to create an interactive SVG where changing certain custom attributes changes the SVG but I ran into a bit of a trouble - I want to switch between different air vent system modes by passing the name of the mode as an attribute and I couldn't find an easy way to hide or show different icons for those modes.


Basically the question is - is there any way to use the value of an element's attribute as a selector without knowing what the value is beforehand?


Consider this CSS code:

#root[Mode="some_mode"] [id=attr(Mode)] {
    /* .. style .. */
}

And this SVG code:

<g id="root" Mode="some_mode">
    <g id="mode1" />
    <g id="mode2" />
    <!-- and so on -->
</g>

This seems like the most obvious and logical way to do this but it doesn't work, so I resorted to a hacky way of doing this:

#root[Mode="standby"] #standby { visibility: visible; }
#root[Mode="comfort"] #comfort { visibility: visible; }
#root[Mode="economy"] #economy { visibility: visible; }
/* and so on for every mode that I have */

I know that this can be done using JS but the trick is that this SVG has to be JS-less (it's for a SCADA system that uses SVGs for custom graphics).

Thanks in advance for helping!

Since CSS is declarative I think the correct (albeit verbose) approach really is:

[Mode="standby"] #standby,
[Mode="comfort"] #comfort,
[Mode="economy"] #economy {
  visibility: visible;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM