如何根据旋转角度动态调整伪元素高度?
解决方案
核心调整点
- 修复伪元素的旋转中心,确保始终以父元素中心旋转
- 根据矩形宽高比,动态计算不同旋转角度下伪元素的高度,实现水平方向(左右边框)高度缩小、垂直方向(上下边框)高度放大的效果
修改后的完整代码
import React, { useState, useEffect } from "react"; import styled, { keyframes } from "styled-components"; const Box = styled.div` position: relative; width: 510px; height: 90px; display: flex; justify-content: center; align-items: center; background-color: blue; border-radius: 20px; overflow: hidden; // 隐藏超出父元素的伪元素部分 &::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(${props => props.rotationDegree}deg); transform-origin: center; width: 500px; // 保持与父元素内框宽度匹配 height: ${props => { const parentWidth = 510; const parentHeight = 90; const rad = (props.rotationDegree * Math.PI) / 180; const sin = Math.abs(Math.sin(rad)); const cos = Math.abs(Math.cos(rad)); // 左右边框时的最小高度(可按需调整) const minHeight = parentHeight * 0.8; // 覆盖上下边框对角线的最大高度,加1.1留余量 const maxHeight = Math.sqrt((parentWidth/2)**2 + (parentHeight/2)**2) * 2 * 1.1; // 水平方向主导时用小高度,垂直方向主导时用大高度 return cos > sin ? `${minHeight}px` : `${maxHeight}px`; }}; background: linear-gradient(#00ccff, #d500f9); animation: rotateGlow 4s linear infinite; } &::after { content: ''; position: absolute; background: #0e1538; inset: 5px; border-radius: 16px; } `; // 提取独立动画规则,避免重复生成 const rotateGlow = keyframes` from { transform: translate(-50%, -50%) rotate(0deg); } to { transform: translate(-50%, -50%) rotate(360deg); } `; function App() { const [rotationDegree, setRotationDegree] = useState(0); useEffect(() => { const interval = setInterval(() => { setRotationDegree((prevDegree) => (prevDegree + 1) % 360); }, 4000 / 360); return () => clearInterval(interval); }, []); return ( <div> <Box rotationDegree={rotationDegree}>{/* Content inside the Box */}</Box> <span>{rotationDegree}</span> </div> ); } export default App;
关键说明
- 旋转中心修复:通过
top:50%; left:50%; transform: translate(-50%, -50%)让伪元素锚定父元素中心,旋转时不会偏移。 - 动态高度逻辑:
- 用
cos > sin判断当前角度是水平方向主导(左右边框阶段)还是垂直方向主导(上下边框阶段) - 水平阶段使用接近父元素高度的小值,仅露出左右边框的发光效果;垂直阶段使用对角线计算的大值,确保上下边框区域有足够的发光范围
- 用
- 性能优化:将旋转动画提取为独立
keyframes,避免组件每次渲染时重新生成动画规则。
内容的提问来源于stack exchange,提问作者Angel Hadzhiev
相关产品推荐
相关产品推荐

