前言
在上一篇文章4.1.2节中介绍了时钟刻度的实现方式,对其中时钟数字的摆放位置我们总结出了一套公式进行计算,本篇对数字的摆放给出了更简洁的实现方式。
改进思路
利用伪元素before,我们可以将数字附加到刻度之前,因为数字会跟着刻度旋转,所以为了保证数字正常显示,我们需要再针对数字进行一次旋转。即总共进行两次旋转,一次整体旋转,一次数字旋转。
同时,为了让刻度和数字完全对齐,我们需要在设置伪元素的样式上使用一些技巧。
代码与细节展示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| <!DOCTYPE html> <html>
<head> <meta charset="utf-8"> <style> #clock { width: 300px; height: 300px; border-radius: 50%; border: 1px solid; font-size: 20px; position: relative; } .scale>div { position: absolute; height: 5px; width: 2px; left: 50%; background-color: black; transform-origin: 0 150px; } .scale>div:nth-child(5n+1) { height: 10px; } .scale>div:nth-child(5n+1)::before { display: block; text-align: center; width: 20px; margin-left: -10px; } .scale>div:nth-child(1)::before { content: '12'; transform: rotate(0deg); } .scale>div:nth-child(6)::before { content: '1'; transform: rotate(-30deg); } </style> <title>clock</title> </head>
<body> <div id="clock"> <div class="scale"> <div class='scale0' style="transform: rotate(0deg);"></div> <div class='scale1' style="transform: rotate(6deg);"></div> <div class='scale2' style="transform: rotate(12deg);"></div> <div class='scale3' style="transform: rotate(18deg);"></div> <div class='scale4' style="transform: rotate(24deg);"></div> <div class='scale5' style="transform: rotate(30deg);"></div> </div> </div> </body>
</html>
|
眼见为实
后记
当然,旋转两次的思路并不是只能用伪元素来实现,只是个人觉得伪元素应用于此让代码显得比较优雅。