我们可以在CSS中指定自定义数据属性值吗? [英] Can we specify custom data attribute values in CSS?

查看:169
本文介绍了我们可以在CSS中指定自定义数据属性值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在元素上我可以指定数据属性,例如

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>

有没有办法在CSS中指定数据属性值?

Is there a way to specify data attribute values in CSS?

推荐答案

CSS不是HTML。您无法使用CSS设置或更改HTML属性的值。

CSS is not HTML. You cannot set or change the value of an HTML attribute using CSS.

此外,您为什么要这样做?由于关注点分离,存在HTML和CSS。 HTML用于内容,CSS用于演示。在CSS中指定数据属性与在HTML中指定表示属性没有什么不同。

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.

如果您尝试将元数据分配给类名,然后将其应用于具有该类的所有元素类名,这(完全)完全在CSS的范围之外,并且在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.)

这篇关于我们可以在CSS中指定自定义数据属性值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆