@property允许开发者显式地定义他们的CSS自定义属性,允许进行属性类型检查、设定默认值以及定义该自定义属性是否可以被继承
在一般css场景中,诸如背景色渐变等是无法过渡的,但使用@property后,可指定属性过渡,而非整个背景过渡,实现过渡效果
(1)定义css自定义属性
css中:
@property --property-name { 名称和css定义变量规则一致
syntax: '<color>'; 属性类型,必填
inherits: false; 该自定义属性是否可以被继承,必填
initial-value: #fff; 设定默认值,非必填
}
p {
color: var(--property-name);
}
js中:
CSS.registerProperty({
name: "--property-name",
syntax: "<color>",
inherits: false,
initialValue: "#c0ffee"
});
支持的属性类型:
length npx
number
percentage 百分比
length-percentage
color
image
url
integer
angle
time
resolution
transform-list
transform-function
custom-ident (a custom identifier string)
属性类型符合操作
syntax: '<类型#>' 接受逗号分隔的值列表
如: red,yellow
syntax: '<类型+>' 接受以空格分隔的长度值列表
如:red yellow
syntax: '<类型 | 类型+ | 类型#>' 接受单个长度或空格分隔的长度或逗号分隔的值列表,类型可以是任意类型
如:red 或 red yellow 或 red,yellow
(2)使用和修改@property
使用:
var(定义的变量名称)
var(定义的变量名称,默认值) 当@property未定义默认值时
修改:
定义的变量名称:新值
(3)transition过渡写法:
1、定义@property
@property --houdini-colorA {
syntax: '<color>';
inherits: false;
initial-value: #fff;
}
@property --houdini-colorB {
syntax: '<color>';
inherits: false;
initial-value: #000;
}
2、设置过渡时间等
.property {
background: linear-gradient(45deg, var(--houdini-colorA), var(--houdini-colorB));
transition: 1s --houdini-colorA, 1s --houdini-colorB;
}
3、改变属性值进行过渡:
.property:hover {
--houdini-colorA: yellowgreen;
--houdini-colorB: deeppink;
}
(4)animation过渡写法:
div {
background: linear-gradient(45deg,
var(--colorA),
var(--colorC),
var(--colorF));
animation: change 10s infinite linear;
}
@keyframes change {
20% {
--colorA: red;
--colorC: #a93ee0;
--colorF: fuchsia;
}
...
}
代码示例:
渐变背景色过渡:
@property --colorA {
syntax: '<color>';
inherits: false;
initial-value: fuchsia;
}
@property --colorC {
syntax: '<color>';
inherits: false;
initial-value: #f79188;
}
@property --colorF {
syntax: '<color>';
inherits: false;
initial-value: red;
}
div {
background: linear-gradient(45deg,
var(--colorA),
var(--colorC),
var(--colorF));
animation: change 10s infinite linear;
}
@keyframes change {
20% {
--colorA: red;
--colorC: #a93ee0;
--colorF: fuchsia;
}
40% {
--colorA: #ff3c41;
--colorC: #e228a0;
--colorF: #2e4c96;
}
60% {
--colorA: orange;
--colorC: green;
--colorF: teal;
}
80% {
--colorA: #ae63e4;
--colorC: #0ebeff;
--colorF: #efc371;
}
}
渐变背景百分比过渡:
@property --per {
syntax: '<percentage>';
inherits: false;
initial-value: 25%;
}
div {
background: conic-gradient(yellowgreen, yellowgreen var(--per), transparent var(--per), transparent 100%);
transition: --per 300ms linear;
&:hover {
--per: 60%;
}
}
下划线位移动画:
@property --offset {
syntax: '<length>';
inherits: false;
initial-value: 0;
}
div {
text-underline-offset: var(--offset, 1px);
text-decoration: underline;
transition: --offset 400ms, text-decoration-color 400ms;
&:hover {
--offset: 10px;
color: orange;
text-decoration-color: orange;
}
}