效果预览

在线演示

按下右侧的“点击预览”按钮可以在当前页面预览,点击链接可以全屏预览。

https://codepen.io/comehope/pen/rvgLzK

可交互视频教程

此视频是可以交互的,你可以随时暂停视频,编辑视频中的代码。

请用 chrome, safari, edge 打开观看。

https://scrimba.com/p/pEgDAM/cW7gZfb

源代码下载

本地下载

每日前端实战系列的全部源代码请从 github 下载:

https://github.com/comehope/front-end-daily-challenges

代码解读

定义 dom,容器中包含左拍、小球和右拍:

<div class="court">
<div class="left-paddle"></div>
<div class="ball"></div>
<div class="right-paddle"></div>
</div>

居中显示:

body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(silver, dimgray);
}

调整盒模型:

* {
box-sizing: border-box;
}

画出球案:

.court {
width: 20em;
height: 20em;
color: white;
border: 1em solid currentColor;
}

画出左拍:

.court {
position: relative;
} .left-paddle
width: 1em;
height: calc(50% - 1em);
background-color: currentColor;
position: absolute;
top: 1em;
left: 1em;
}

让左拍动起来:

.left-paddle {
animation: left-moving 1s linear infinite alternate;
} @keyframes left-moving {
to {
transform: translateY(100%);
}
}

类似地,画出右拍:

.right-paddle
width: 1em;
height: calc(50% - 1em);
background-color: currentColor;
position: absolute;
top: 1em;
left: 1em;
bottom: 1em;
right: 1em;
}

类似地,让右拍动起来:

.right-paddle {
animation: right-moving 1s linear infinite alternate;
} @keyframes right-moving {
to {
transform: translateY(-100%);
}
}

画出小球:

.ball {
width: 100%;
height: 1em;
border-left: 1em solid currentColor;
position: absolute;
left: 2em;
top: calc(50% - 1.5em);
}

让小球动起来:

.ball {
animation: bounce 1s linear infinite alternate;
} @keyframes bounce {
to {
left: calc(100% - 3em);
}
}

最后,重构一下左右拍的代码,合并共有属性:

.left-paddle,
.right-paddle {
width: 1em;
height: calc(50% - 1em);
background-color: currentColor;
position: absolute;
animation: 1s linear infinite alternate;
} .left-paddle {
top: 1em;
left: 1em;
animation-name: left-moving;
} .right-paddle {
bottom: 1em;
right: 1em;
animation-name: right-moving;
}

大功告成!

原文地址:https://segmentfault.com/a/1190000015002553

最新文章

  1. python leetcode 1
  2. Task:取消异步计算限制操作 & 捕获任务中的异常
  3. 【BZOJ-4523】路由表 Trie树 + 乱搞
  4. PHP实现站点pv,uv统计(一)
  5. Mysql的权限管理
  6. NodeAsp——像开发NodeJS应用一样玩转ASP
  7. wininet API调用,检测网络
  8. jQuery事件与事件对象
  9. SpringMVC的值传递
  10. Swift - 可选类型说明
  11. Reeder Web版
  12. Qt 5.7 > QML
  13. Storm 分配逻辑
  14. error_reporting
  15. c#源码如何生成托管代码块
  16. 聊聊IOCP,聊聊异步编程
  17. 深入学习sequoiadb巨杉数据库及python连接方式
  18. Socket网络编程--聊天程序(3)
  19. Django框架详解
  20. Error:java: 无效的源发行版: 1.8

热门文章

  1. 「Luogu P5603」小O与桌游
  2. redux异步
  3. 浅析java中的四种线程池
  4. 解决Git 报错:warning: LF will be replaced by CRLF
  5. [go]beego获取参数/返回参数
  6. LC 672. Bulb Switcher II
  7. .NET GC简单理解
  8. 前端使用 fabric 进行部署
  9. distinct 与group by 去重
  10. [git]查看一个git项目的仓库位置