You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据旋转角度动态调整伪元素高度?

解决方案

核心调整点

  • 修复伪元素的旋转中心,确保始终以父元素中心旋转
  • 根据矩形宽高比,动态计算不同旋转角度下伪元素的高度,实现水平方向(左右边框)高度缩小、垂直方向(上下边框)高度放大的效果

修改后的完整代码

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;

关键说明

  1. 旋转中心修复:通过top:50%; left:50%; transform: translate(-50%, -50%)让伪元素锚定父元素中心,旋转时不会偏移。
  2. 动态高度逻辑:
    • 用cos > sin判断当前角度是水平方向主导(左右边框阶段)还是垂直方向主导(上下边框阶段)
    • 水平阶段使用接近父元素高度的小值,仅露出左右边框的发光效果;垂直阶段使用对角线计算的大值,确保上下边框区域有足够的发光范围
  3. 性能优化:将旋转动画提取为独立keyframes,避免组件每次渲染时重新生成动画规则。

内容的提问来源于stack exchange,提问作者Angel Hadzhiev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 03:56:19