自学内容网 自学内容网

前端子元素均匀分布在圆上,并旋转整体旋转,子元素不动

在这里插入图片描述
纯用css js就能实现

<!-- 元素 -->
<body>
  <div class="box">
    <div class="item">
      <div>s1</div>
    </div>
    <div class="item">
      <div>s2</div>
    </div>
    <div class="item">
      <div>s3</div>
    </div>
    <div class="item">
      <div>s4</div>
    </div>
    <div class="item">
      <div>s5</div>
    </div>
  </div>
</body>
  <style>
    .box{
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 200px;
      width: 200px;
      height: 200px;
      border: 2px dashed pink;
      border-radius: 50%;
      animation: rotate 20s linear infinite;
    }
    .item{
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: green;
    }
    /* 设置反向旋转 */
    .item div{
      animation: rotate 20s linear infinite reverse;
    }

    @keyframes rotate {
      to {
        transform: rotate(360deg);
      }
    }
  </style>
  <script>
    const r = document.querySelector('.box').clientWidth / 2
    const items = document.querySelectorAll('.item')

    // 使用正弦函数和余弦函数计算每个元素的位置
    items.forEach((item, index) => {
      const t = index * (360 / items.length) * (Math.PI / 180)
      const x = r * Math.sin(t)
      const y = -r * Math.cos(t)
      item.style.transform = `translate(${x}px, ${y}px)`
    })
  </script>

原文地址:https://blog.csdn.net/qq_41064597/article/details/143866562

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!