问题
On elements I can specify the data attributes as, e.g.
<div data-widget-type="MyWidgetType1" data-property1="20" data-property2="test">
...
</div>
I want to capture these in a class e.g.
.MyClass1 {
data-widget-type:"MyWidgetType1";
data-property1:"20";
data-property2:"test";
}
<div class="MyClass1">
...
</div>
Is there a way to specify data attribute values in CSS?
回答1:
CSS is not HTML. You cannot set or change the value of an HTML attribute using CSS.
Besides, why would you do this? HTML and CSS exist because of separation of concerns. HTML is for content and CSS is for presentation. Specifying data attributes in CSS is no different to specifying presentational attributes in HTML.
If you're trying to assign metadata to a class name which then applies to all elements with that class name, that's (again) completely outside of the purview of CSS, and simply not possible in HTML. The only way to assign metadata to an element is to specify it as an attribute on that element. (You can move the attribute declarations to a script if you don't want to specify the attributes on every instance of that class within the markup, but at the end of the day the script still has to populate each element's dataset with those values. Depending on your needs, though, this may be sufficient.)
回答2:
It's possible to select a class in css using the [attribute] value, but I don't believe CSS can update that attribute.
https://css-tricks.com/almanac/selectors/a/attribute/
To update the attribute you'd need to find a jQuery solution, or similar.
Edit: In jQuery, you can update the attribute like this:
$("#fieldId").attr("attribute-name","value you want to set");
回答3:
There is a way to get the value of your attributes, but it's not supported for all the browsers:
https://developer.mozilla.org/en-US/docs/Web/CSS/attr
I don't know if this is what you are looking for
回答4:
No, there is no such functionality even for default attributes (like you can't set name attribute via CSS). But you can select these custom attributes:
.MyClass1[data-widget-type="MyWidgetType1"]
来源:https://stackoverflow.com/questions/36565685/can-we-specify-custom-data-attribute-values-in-css