Css变量使用
// 需求:设置一个动画使一个小球在一个元素中来回滚动,元素宽度不固定
import React, { Component } from 'react'
import './index.less'
// css 变量使用
// 需求:设置一个动画使一个小球在一个元素中来回滚动,元素宽度不固定
export default class Test12 extends Component {
componentDidMount(): void {
const contioner = document.querySelector('.contioner')
const item = document.querySelector('.item')
const scrollableWidth = contioner?.clientWidth - item.clientWidth // 可滚动范围为容器元素宽度-自身宽度
item.style.setProperty('--w', `${scrollableWidth}px`) // 为item滚动元素设置自定义属性--w,宽度为可滚动宽度
}
render() {
return (
<div className="contioner">
<div className="item"></div>
</div>
)
}
}
css 部分
.contioner{
width: 80%;
height: 300px;
border:1px solid black;
.item{
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
margin-top: 30px;
animation: move 6s linear infinite;
}
}
@keyframes move{
50%{
transform: translateX(calc(var(--w)));
}
}