Html 使用 HTML5 数据属性的 CSS 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9523197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS values using HTML5 data attribute
提问by James Kyle
width: attr(data-width);
I want to know if there's any way it's possible to set a css value using HTML5's data-
attribute the same way that you can set css content
. Currently it doesn't work.
我想知道是否有任何方法可以像设置 css 一样使用 HTML5 的data-
属性设置 css 值content
。目前它不起作用。
HTML
HTML
<div data-width="600px"></div>
CSS
CSS
div { width: attr(data-width) }
采纳答案by Caio Cunha
There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation
确实有这样的功能,看看http://www.w3.org/TR/css3-values/#attr-notation
This fiddleshould work like what you need, but will not for now.
这个小提琴应该像你需要的那样工作,但现在不会。
Unfortunately, it's still a draft, and isn't fully implemented on major browsers.
不幸的是,它仍然是一个草案,并没有在主要浏览器上完全实现。
It does work for content
on pseudo-elements, though.
不过,它确实适用content
于伪元素。
回答by yckart
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
您可以使用 javascript 创建一些 css- rules
,稍后您可以在您的样式中使用它们:http: //jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
这将创建 100 个像这样的伪选择器:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
注意:这有点离题,并不是您(或某人)真正想要的,但可能会有所帮助。
回答by Benny Neugebauer
As of today, you can read some values from HTML5 data
attributes in CSS3 declarations. In CaioToOn's fiddlethe CSS code can use the data
properties for setting the content
.
从今天起,您可以从data
CSS3 声明中的HTML5属性中读取一些值。在CaioToOn 的小提琴中,CSS 代码可以使用data
属性来设置content
.
Unfortunately it is not working for the width
and height
(tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).
不幸的是,它不适用于width
和height
(在 Google Chrome 35、Mozilla Firefox 30 和 Internet Explorer 11 中测试)。
But there is a CSS3 attr() Polyfillfrom Fabrice Weinberg which provides support for data-width
and data-height
. You can find the GitHub repo to it here: cssattr.js.
但是有一个来自 Fabrice Weinberg的CSS3 attr() Polyfill,它为data-width
和提供支持data-height
。您可以在此处找到它的 GitHub 存储库:cssattr.js。