最近要实现一个长按两秒,然后显示圆环倒数进度条的动画。 不想找轮子,想自己写来试试。

原理

由一个白色和蓝色两个圈组成,选择白色为底色,即白色的圆在下面,蓝色圈分为两个半圆,分别运动到白色圈的上面。

1.如何画一个半圆环

(1)正方形画一半的边
方法不好用,一是border的分段出来有45度的旋转,二是元素余出大量空间,这一点导致我一直因为元素zindex的问题无法实现,因为这种实现方式形成了一个环,最上面的元素最后要藏在最下面的元素下(花了我一晚上的时间,脑壳都想破了也没想出来,最后参考别人用了第二种矩形的方法)。

  1. .box {
  2. width: 200px;
  3. height: 200px;
  4. border-radius: 50%;
  5. border: 2px solid red;
  6. border-top-color: transparent;
  7. border-right-color: transparent;
  8. }

image.png
(2)矩形border-radius设为短边,大小两个圆构成圆环。不能用border来画,否则是下图二的样子。

  1. .box {
  2. width: 80px;
  3. height: 160px;
  4. border-top-left-radius: 80px;
  5. border-top-right-radius: 0px;
  6. border-bottom-right-radius: 0px;
  7. border-bottom-left-radius: 80px;
  8. }

image.png image.png

2.如何让圆转圈

  1. 定义按照rotate行动
  2. 定义旋转中心transform-origin

3.如何让动画停在最后一帧

animation-fill-mode: forwards

4.伪类为什么会偏移

在父元素有border的时候,伪类元素会在border结束的地方开始绘制

附上源码

  1. <div class="loading">
  2. <div class="left"></div>
  3. <div class="right"></div>
  4. <div class="progress"></div>
  5. </div>
  6. .loading .progress {
  7. position: absolute;
  8. width: 120px;
  9. height: 120px;
  10. background-color: #000;
  11. border-radius: 50%;
  12. left: 20px;
  13. top: 20px;
  14. line-height: 120px;
  15. text-align: center;
  16. }
  17. .left,
  18. .right {
  19. width: 80px;
  20. height: 160px;
  21. overflow: hidden;
  22. position: relative;
  23. float: left;
  24. background-color: #fff;
  25. }
  26. .left {
  27. border-radius: 80px 0 0 80px;
  28. }
  29. .right {
  30. border-radius: 0 80px 80px 0;
  31. }
  32. .left:after,
  33. .right:after {
  34. content: "";
  35. position: absolute;
  36. display: block;
  37. width: 80px;
  38. height: 160px;
  39. border-radius: 80px 0 0 80px;
  40. background-color: blue;
  41. animation-duration: 2s;
  42. animation-iteration-count: infinite;
  43. animation-timing-function: linear;
  44. }
  45. .right:after {
  46. content: "";
  47. position: absolute;
  48. display: block;
  49. border-radius: 0 80px 80px 0;
  50. }
  51. .left:after {
  52. transform-origin: right center;
  53. animation-name: spin-left;
  54. }
  55. .right:after {
  56. transform-origin: left center;
  57. animation-name: spin-right;
  58. }
  59. @keyframes spin-right {
  60. 0 {
  61. transform: rotate(0deg);
  62. }
  63. 50% {
  64. transform: rotate(180deg);
  65. }
  66. 100% {
  67. transform: rotate(180deg);
  68. }
  69. }
  70. @keyframes spin-left {
  71. 0 {
  72. transform: rotate(0deg);
  73. }
  74. 50% {
  75. transform: rotate(0deg);
  76. }
  77. 100% {
  78. transform: rotate(180deg);
  79. }
  80. }

1.scss的keyframe写法
3.原理(究竟为什么能实现转圈后消失)