我想在我的应用程序中使用动画,但它需要 SCSS 中的 @property 函数:
@property --border-angle {
syntax: "<angle>";
inherits: true;
initial-value: 0turn;
}
有没有办法在样式组件中做到这一点?
动画的完整代码位于:https://codepen.io/shshaw/pen/RwJwJJx
或者如何重写这个函数,使其不必使用 property 函数?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
正如我测试的那样,发布的代码似乎确实可以与
styled-components一起使用,尽管浏览器似乎支持@property仍然受到限制,例如它适用于 Chrome,但目前不适用于 Firefox,因此不会在其上播放渐变动画。我尝试创建所发布代码的替代版本,而不使用
@property,它也可以在 Firefox 上运行。如果它有用,这里有一个演示: stackblitz (代码包含在答案末尾)。原始发布的代码已使用以下示例进行了测试:stackblitz (Firefox 目前不支持
@property的渐变动画)。// Styled components const Container = styled.div` height: 100%; background: #223; display: grid; place-items: center; `; const Box = styled.div` --border-size: 3px; --border-angle: 0turn; width: 60vmin; height: 50vmin; background-image: conic-gradient( from var(--border-angle), #213, #112 50%, #213 ), conic-gradient(from var(--border-angle), transparent 20%, #08f, #f03); background-size: calc(100% - (var(--border-size) * 2)) calc(100% - (var(--border-size) * 2)), cover; background-position: center center; background-repeat: no-repeat; animation: bg-spin 3s linear infinite; @keyframes bg-spin { to { --border-angle: 1turn; } } &:hover { animation-play-state: paused; } @property --border-angle { syntax: "";
inherits: true;
initial-value: 0turn;
}
`;
export default function App() {
return (
);
} 下面是没有
@property的替代版本进行比较,它使用伪元素并添加了子div来在styled-components中重新创建动画。现场演示:stackblitz(也应该有效)对于火狐浏览器)。
// Styled components const Container = styled.div` min-height: 100vh; background: #223; display: grid; place-items: center; `; const Box = styled.div` width: 60vmin; height: 50vmin; position: relative; overflow: hidden; &::before { content: ""; position: absolute; inset: 0; background-image: conic-gradient(from 0turn, transparent 20%, #08f, #f03); animation: fallback-spin 3s linear infinite; } @keyframes fallback-spin { to { transform: scale(1000%) rotate(1turn); } } &:hover::before { animation-play-state: paused; } &:hover > div::before { animation-play-state: paused; } `; const Fallback = styled.div` position: absolute; inset: 3px; overflow: hidden; background-color: pink; &::before { content: ""; position: absolute; inset: 0; background-image: conic-gradient(from 0turn, #213, #112 50%, #213); animation: fallback-spin 3s linear infinite; } @keyframes fallback-spin { to { transform: scale(1000%) rotate(1turn); } } `; export default function App() { return (
);
}顺便说一句,@property是较新的标准 CSS。有关@property的更多背景信息,请参见 MDN。 p>