将 CSS3 attr() 与变换旋转结合使用
Using CSS3 attr() with transform rotate
我希望能够在 CSS 中通过一个属性进行旋转,即
<my-object data-angle="225"></my-object>
我目前的CSS是
transform:rotate(attr(data-angle)deg);
但这会引发错误,正确的语法是什么?
这在目前的浏览器中是不可能的。但是规范说:
The attr() CSS function is used to retrieve the value of an attribute
of the selected element and use it in the style sheet. It can be used
on pseudo-elements too and, in this case, the value of the attribute
on the pseudo-element's originated element is returned.
The attr() function can be used with any CSS property, but support for
properties other than content is experimental.
所以在不久的将来会支持。
这是 MDN 文档。
我不抱任何希望他们会完全按照 Asim 指出的标准实施,但好消息是你可以用 Custom Properties aka CSS variables
有一个 Javascript API for DOM 元素来获取和设置这些变量
el.style.setProperty('--foo', 'my custom property value')
或者如果您不介意内联 style
属性,您甚至可以直接在 HTML 中设置它:
<div style='--foo:"my custom prop val";'>
这是一个示例(您对这段代码的了解可能会有所不同,具体取决于您的浏览器对自定义属性的支持):
:root {
--rotation: 5deg;
}
.rotate {
padding: 0.2em;
transition: transform .2s;
will-change: transform;
}
.rotate:hover {
transform: rotate(var(--rotation));
}
.more {
--rotation: 15deg;
}
<button class='rotate'>rotation</button>
<button class='rotate more'>more rotation</button>
<button class='rotate' style='--rotation: 30deg;'>yet more rotation</button>
我希望能够在 CSS 中通过一个属性进行旋转,即
<my-object data-angle="225"></my-object>
我目前的CSS是
transform:rotate(attr(data-angle)deg);
但这会引发错误,正确的语法是什么?
这在目前的浏览器中是不可能的。但是规范说:
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the style sheet. It can be used on pseudo-elements too and, in this case, the value of the attribute on the pseudo-element's originated element is returned.
The attr() function can be used with any CSS property, but support for properties other than content is experimental.
所以在不久的将来会支持。
这是 MDN 文档。
我不抱任何希望他们会完全按照 Asim 指出的标准实施,但好消息是你可以用 Custom Properties aka CSS variables
有一个 Javascript API for DOM 元素来获取和设置这些变量
el.style.setProperty('--foo', 'my custom property value')
或者如果您不介意内联 style
属性,您甚至可以直接在 HTML 中设置它:
<div style='--foo:"my custom prop val";'>
这是一个示例(您对这段代码的了解可能会有所不同,具体取决于您的浏览器对自定义属性的支持):
:root {
--rotation: 5deg;
}
.rotate {
padding: 0.2em;
transition: transform .2s;
will-change: transform;
}
.rotate:hover {
transform: rotate(var(--rotation));
}
.more {
--rotation: 15deg;
}
<button class='rotate'>rotation</button>
<button class='rotate more'>more rotation</button>
<button class='rotate' style='--rotation: 30deg;'>yet more rotation</button>