子元素使用transform旋转后没有撑起父元素
问题:
子元素使用transform:rotate(90deg) 旋转90度,并没有如愿的自动将父元素撑开宽高,那么,如何正常的撑开父元素(高宽对应)
思路:
在旋转后,我们可通过获取子元素当前的宽高,来赋值给父元素,那么,代码如下:
注意:需要注意的是,我们需要判断当前是否为已旋转,如果已旋转,那么就需要将子元素的宽赋值给父元素的高,因为子元素已经做了旋转,宽高互调。
js:
import React, { useState, useEffect, useRef } from 'react';
import { Button } from 'antd';
import styles from './index.less';
export default function RotateBox() {
const [rotateDeg, setRotateDeg] = useState(0)
const [viewWidth, setViewWidth] = useState()
const [viewHeight, setViewHeight] = useState()
const containerRef = useRef(null);
const rotatePage = (type) => {
console.log('typp', type)
if (type === 'LEFT') {
setRotateDeg(rotateDeg - 90)
} else {
setRotateDeg(rotateDeg + 90)
}
}
useEffect(() => {
// const width = Math.abs(rotateDeg % 180) === 90 ? containerRef.current.offsetHeight : containerRef.current.offsetWidth
const height = Math.abs(rotateDeg % 180) === 90 ? containerRef.current.offsetWidth : containerRef.current.offsetHeight
// setViewWidth(width);
setViewHeight(height);
}, [rotateDeg])
return (
<div className={styles.content}>
<div className={styles.box} style={{
// width: viewWidth,
height: viewHeight
}}>
<div ref={containerRef} className={styles['box-rotate']} style={{ transform: `rotate(${rotateDeg}deg)` }} />
</div>
<div className={styles.btns}>
<Button onClick={() => rotatePage('LEFT')}>向左旋转</Button>
<Button onClick={() => rotatePage('RIGHT')}>向右旋转</Button>
</div>
</div>
)
}
css:
.content {
width: 100%;
.box {
width: 100%;
min-width: 100px;
min-height: 100px;
display: flex;
align-items: center;
justify-content: space-between;
background-color: #eee;
overflow: hidden;
&-rotate {
width: 100%;
height: 30px;
background-color: #aaa;
}
}
.btns {
width: 100%;
text-align: center;
}
}
THE END
分类:
CSS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类