【问题标题】:Basic Animation HTML and CSS基本动画 HTML 和 CSS
【发布时间】:2022-01-19 20:21:06
【问题描述】:

所以我只是一个初学者,我只是想弄清楚动画以及它们是如何工作的。

我的计划是让球在一条直线上以无限度数(比如 90 度)无限移动。以下是我想知道的几个问题:

  1. 有没有更好的方法来使用具有共同但略有不同规则(具有不同旋转)的类?
  2. 如何让球在具有不同旋转的新线上运动?

.line,
.line-deg90 {
  background-color: hsl(0, 0%, 0%);
  height: 3px;
  width: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: 0 0 0 -200px;
  transform-origin: 50%;
}

.line-deg90 {
  transform: rotate(90deg);
}

.ball {
  background-color: hsl(0, 0%, 0%);
  height: 30px;
  width: 30px;
  border-radius: 50%;
  position: absolute;
  top: -15px;
  left: 0;
  animation: move 2s infinite alternate ease-in-out;
}

@keyframes move {
  0% {
    left: 0px;
    top: -15px;
  }

  100% {
    left: 370px;
    top: -15px;
  }
<div class="line">
  <div class="ball"></div>
<div class="line-deg90"></div>

【问题讨论】:

    标签: html css css-animations css-transforms


    【解决方案1】:

    这是一个使用 CSS 变量来获得通用代码的想法。只需调整角度和偏移量即可控制运动

    .ball {
      --angle: 0deg;
      --offset: 150px;
      
      background-color: hsl(0, 0%, 0%);
      height: 30px;
      width: 30px;
      border-radius: 50%;
      position: absolute;
      inset: 0;
      margin: auto;
      animation: move 2s infinite alternate ease-in-out;
    }
    
    @keyframes move {
      0% {
        transform: rotate(var(--angle)) translate(var(--offset))
      }
      100% {
        transform: rotate(var(--angle)) translate(calc(-1*var(--offset)))
      }
    }
    
    
    html {
      min-height:100%;
      background:
        linear-gradient(red 0 0) center/100% 2px,
        linear-gradient(red 0 0) center/2px 100%;
      background-repeat:no-repeat;
    }
    <div class="ball"></div>
    <div class="ball" style="--angle:90deg;--offset:100px"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-13
      • 2011-07-06
      • 1970-01-01
      • 2013-06-09
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多