【问题标题】:animate element from center of view to its original position将元素从视图中心动画到其原始位置
【发布时间】:2021-02-27 04:49:43
【问题描述】:

我想创建一个动画来将元素从当前视图的中心移动到原始位置。

但是CSS动画不支持切换display属性,所以你会看到下图中第二个矩形没有从中心移动(实际上是用position:absolute动画)。

是否有任何纯 CSS 解决方案来实现目标?任何建议表示赞赏。

以下是我目前尝试过的:

.instruction-target {
  position: relative;
}
.highlight-box {
  width: 100px;
  height: 20px;
  font-weight: bold;
  font-size: 2em;
  border: solid 5px red;
  display: inline-block;
}

.float-highlight-box {
  position: absolute;
  top: 0; 
  left: 0;
  animation-name: moving-to-target;
  animation-duration: 3s;
  opacity: 0;
}

@keyframes moving-to-target {
  /* animate from: center of current view */
  from {
    top: 50vh;
    left: 50vw;
    position: fixed;
    opacity: 1;
  }
  /* animate to: its original position */
  to {
    top: 0px; 
    left: 0px; 
    //position: absolute; 
    opacity: 0;
  }
}
<div style="width: 100%; min-height: 400px;border: solid 1px blue">
  <a style="position:fixed;top: 50vh; left: 50vw;">CENTER</a>
  <button class="instruction-target">
    Test1
    <span class="highlight-box float-highlight-box"></span>
  </button>
  <button class="instruction-target" style="margin-left: 400px">
    Test2
    <span class="highlight-box float-highlight-box"></span>
  </button>
</div>

【问题讨论】:

  • 你可以使用 JavaScript 还是必须是 CSS。
  • @TobyHarnish,OP 说纯 CSS。

标签: html css


【解决方案1】:

使用纯 CSS 可以做到这一点,但必须使用 CSS 变量属性。

这里我保存了一个working example.。

我还在下面添加了一个有效的 sn-p 代码,以便您对其进行测试。

:root {
  --target-offset: 0px;
}

.target-offset {
  --target-offset: 400px;
}

.fixed-center {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.instruction-target {
  position: relative;
}
.highlight-box {
  width: 100px;
  height: 20px;
  font-weight: bold;
  font-size: 2em;
  border: solid 5px red;
  display: inline-block;
}

.float-highlight-box {
  position: fixed;
  top: 0;
  left: var(--target-offset);
  animation-name: moving-to-target;
  animation-duration: 3s;
  opacity: 1;
}

@keyframes moving-to-target {
  /* animate from: center of current view */
  from {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    position: fixed;
    opacity: 1;
  }
  /* animate to: its original position */
  to {
    top: 0px;
    left: var(--target-offset);
    opacity: 0;
  }
}
<div style="width: 100%; min-height: 400px;border: solid 1px blue">
  <a class="fixed-center">CENTER</a>
  <button class="instruction-target">
    Test1
    <span class="highlight-box float-highlight-box"></span>
  </button>
  <button class="instruction-target target-offset" style="margin-left: var(--target-offset)">
    Test2
    <span class="highlight-box float-highlight-box"></span>
  </button>
</div>

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2012-04-21
    • 2011-12-08
    • 2015-12-24
    • 1970-01-01
    相关资源
    最近更新 更多