我可以使媒体查询在常规styled-components
组件中正常工作,但是当我尝试在keyframe
中使用它(通过从styled-components
导入)时,它似乎不起作用完全没有。
尝试使div动画到特定位置,但是当窗口<800px时要改变最终位置,我已经尝试过:
import styled, { keyframes } from 'styled-components';
// ... further down ...
const slideAnim = keyframes`
100% {
top: 20px;
left: 30px;
}
@media (max-width: 800px) {
top: 70px;
left: 50px;
}
`;
我还尝试过将媒体查询放在100%
块中:
const slideAnim = keyframes`
100% {
top: 20px;
left: 30px;
@media (max-width: 800px) {
top: 70px;
left: 50px;
}
}
`;
我对要实现的目标进行了有益的交互式演示(问题代码在第24行): https://codesandbox.io/embed/fragrant-star-m71ct
如果需要,可以随时将breakpoint
变量从800更改。
感谢您的帮助!
答案 0 :(得分:1)
您可以采用另一种方法,将keyframes
动画定义为这样的函数:
const slideAnim = (top, left) => keyframes`
100% {
top: ${ top };
left: ${ left };
}
`;
该函数接受输入参数,这些参数规定了该动画的最终关键帧的top
和left
的目标坐标。
在您的stly组件(即Box1
)中,您将为每个断点调用具有特定坐标的slideAnim()
,以实现每个断点不同的动画行为:
/*
Declare responsive styling in the Box1 component, where destination
coordinates are specified for the animate on a per-breakpoint-basis
*/
const Box1 = styled.div`
width: 20px;
height: 20px;
background-color: blue;
position: absolute;
left: -100px;
top: 80px;
&.slide {
animation: ${slideAnim('20px', '30px')} 0.4s ease-in-out forwards;
@media (max-width: ${breakpoint}px) {
animation: ${slideAnim('70px', '50px')} 0.4s ease-in-out forwards;
}
}
`;
总而言之,该想法是将响应式样式转换为样式化的组件(即Box1
),同时定义一个可重复使用的函数,该函数包含每个响应断点的公用/共享keyframes
。
这里是a working example-希望对您有所帮助!
答案 1 :(得分:0)
在所有块之外使用关键帧。例如:
import { IconButton} from "@material-ui/core";
const CloseButton = styled(IconButton)`
padding: 3px !important;
outline: none;
@media only screen and (min-width: 728px) {
padding: 4px !important;
margin:0
}
`;