Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

巧妙使用 CSS 控制动画行进 #63

Open
chokcoco opened this issue Mar 29, 2019 · 3 comments
Open

巧妙使用 CSS 控制动画行进 #63

chokcoco opened this issue Mar 29, 2019 · 3 comments
Labels

Comments

@chokcoco
Copy link
Owner

@chokcoco chokcoco commented Mar 29, 2019

正文从这里开始。

今天要介绍一种很简单的使用 CSS 控制动画播放与暂停的小技巧。使用好了,可以在很多实际场景得以运用。

我们先来看个例子,本例子是我在闲逛 Codepen 时看到了,很有意思:

css-animation1 gif

本例子,CodePen: https://codepen.io/mikegolus/pen/jJzRwJ

上面整个过程都是由 CSS 完成。抛开如何用 CSS 实现上述一些 UI 效果。本文主要讲的是如何只用 CSS 控制一次动画的行进,暂停与开始。

拆解分析需求

上述动画控制要完成的效果是:

  1. 页面 render 后,无任何操作,动画不会开始。只有当鼠标对元素进行 click ,触发元素的 :active 伪类效果的时候,动画才开始进行;
  2. 动画进行到任意时刻,鼠标停止点击,则动画停止;
  3. 重新对元素进行点击,动画继续从上一帧结束的状态开始
  4. 如果动画播放完,再点击不会重复播放,动画状态保留在动画的最后一帧

解决需求

看着好像挺复杂的,其实实现起来很容易,主要借助了伪类 :active 与动画的播放状态 animation-play-state

我们以一个运动的小球做一个简单的示例,小球从左运动到右。

<div></div>
div {
    margin: 50px auto;
    width: 100px;
    height: 100px;
    background: #000;
    animation: move 1s linear;
    animation-fill-mode: forwards;
}

@keyframes move {
    100% {
        transform: translate(200px, 0) rotate(180deg);
    }
}

css-animation2 gif

接下来,我们就进行简单的改造,动画的默认状态是暂停的:

div {
    margin: 50px auto;
    width: 100px;
    height: 100px;
    background: #000;
    animation: move 1s linear;
    animation-fill-mode: forwards;
+   animation-play-state: paused;
}

只有通过点击的时候,动画才会运行:

body:active div {
    animation-play-state: running;
}

看看效果,为了方便看清点击的过程,在点击的过程中,我也改了下背景颜色(背景变色表示当前鼠标按下):
css-animation3 gif

CodePen Demo: https://codepen.io/Chokcoco/pen/XGvwjL

总结一下

嗯,整个过程其实非常简单。理解了这种方法后,就可以随意加到你想的任何动画中,再抛一个类似的 Demo:

css-animation4

CodePen Demo: https://codepen.io/Chokcoco/pen/ZPgxwy

非常有用的一个小技巧,赶紧 GET 起来。

最后,新开通的公众号求关注,形式希望是更短的篇幅,质量更高一些的技巧类文章,包括但不局限于 CSS:

image

@rzdong
Copy link

@rzdong rzdong commented Apr 12, 2019

我有一句nice不知当讲不当讲

@brahmachen
Copy link

@brahmachen brahmachen commented Apr 20, 2019

mark

@chokcoco chokcoco added the 原理 label Jun 6, 2019
@ReGan520
Copy link

@ReGan520 ReGan520 commented Mar 2, 2021

Very Very Good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants