CSS动画设置值[重复]

aydmsdu9  于 2023-02-01  发布在  其他
关注(0)|答案(2)|浏览(99)
    • 此问题在此处已有答案**:

Maintaining the final state at end of a CSS animation(5个答案)
昨天关门了。
你能告诉我如何通过点击按钮来提升块,并且它将保持在位置-25px吗?

$('button').click(function() {
  $('.block').addClass('animation');
})
.block {
  width: 100px;
  height: 100px;
  background: green;
}

.animation {
  animation: up 750ms;
}

@keyframes up {
  0% {
    margin-top: 0px;
  }
  100% {
    margin-top: -25px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block"></div>
<button>UP</button>
6tdlim6h

6tdlim6h1#

你需要把animation-fill-mode: forwards属性添加到.animation类规则中,这将把元素设置为动画完成状态的属性。
animation-fill-mode的文档

$('button').click(function() {
  $('.block').addClass('animation');
})
.block {
  width: 100px;
  height: 100px;
  background: green;
}

.animation {
  animation: up 750ms;
  animation-fill-mode: forwards;
}

@keyframes up {
  0% {
    margin-top: 0px;
  }
  100% {
    margin-top: -25px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block"></div>
<button>UP</button>
jtoj6r0c

jtoj6r0c2#

使用CSS转换而不是边距:

$('button').click(function() {
  $('.block').addClass('animation');
})
.block {
  width: 100px;
  height: 100px;
  background: green;
  transform: translateY(0);
  transition: transform 750ms;
}

.animation {
  transform: translateY(-25px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block"></div>
<button>UP</button>

相关问题