纯css实现的跑马灯动画
const SytledWrapper = styled.div`
width:300px;
height: 50px;
margin: 0 auto;
overflow: hidden;
position: relative;
`
const animationLeft = keyframes`
from{
left:var(--startPos);
}
to{
left:var(--stopPos);
}
`
const StyledScrollDiv = styled.div<{count:number}>`
min-width: 100px;
height: 50px;
display: flex;
position: absolute;
top: 0;
animation: ${({count})=>count * 1}s ${animationLeft} linear infinite;
--startPos:${({count})=>0}px;
--stopPos:${({count})=>-(count >= 3 ? (count-3)*100 : 0)}px;
`
const StyledTextDiv = styled.div<{backgroundColor:string}>`
width: 100px;
height: 50px;
line-height:50px;
text-align:center;
font-size:20px;
font-weight:bold;
background:${({backgroundColor})=>backgroundColor};
`
export const MonMarketEndView: React.FC = () => {
const backgroundColorList = useMemo(() => {
return [
{ color: 'pink' },
{ color: 'green' },
{ color: 'red' },
{ color: 'blue' },
]
}, [])
const scrollList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
return (
<SytledWrapper>
<StyledScrollDiv count={scrollList.length}>
{scrollList.map((info,index)=>(
<StyledTextDiv backgroundColor={backgroundColorList[info%4].color}>
{info}
</StyledTextDiv>
))}
</StyledScrollDiv>
</SytledWrapper>
)
}
利用数组的长度,算出动画时长count*1s
animationLeft指的是向左的动画,通过改版from里面的值来改变动画的效果,比如把left改变为right就是向右的动画啦,var括号里面的是声明的是开始和结束变量,可以是任何名字的
–startPos将开始的动画设置为left:0px,然后结束的动画为什么要设置count-3呢?是怎么算出来的呢?
用数组的长度可显示的长度,可显示的长度为300px,然后一个元素为100px也就是说可以显示3个,所以要减去三,不减去3可以吗?可以的不减去3的话结尾就会留白,减3的目的只是增加了视觉效果,轮播完成后面不会留白