SVG 元素可以像其他 HTML 元素一样在 JavaScript 中操作。在这个例子中,我们使用了一段简短的代码来显示时钟上的实际时间。我们在 JavaScript 中使用 getElementById 访问时针和分针,然后设置它们的 transform 属性反映当前时间的旋转。
这里还有一个技巧值得一提。表示每个小时的点被画成虚线圆圈,这类似于我们可以为常规 HTML 元素设置 border-style CSS 属性,但更复杂。在 SVG 中,我们可以使用 stroke-dasharray 属性微调每个横线的长度和间距。我们也可以使用 stroke-dashoffset 设置偏移量。
SVG 代码:
<svg width="200" height="200" viewBox="-100 -100 200 200">
<rect x="-100" y="-100" width="200" height="200" fill="#CD803D" />
<circle r="55" stroke="#FCCE7B" stroke-width="10" fill="white" />
<circle
r="45"
stroke="#B6705F"
stroke-width="6"
stroke-dasharray="6 17.56194490192345"
stroke-dashoffset="3"
fill="none"
/>
<g stroke="#5f4c6c" stroke-linecap="round">
<line id="hours" y2="-20" stroke-width="8" />
<line id="minutes" y2="-35" stroke-width="6" />
</g>
</svg>
JS 代码:
window.addEventListener("DOMContentLoaded", () => {
const hoursElement = document.getElementById("hours");
const minutesElement = document.getElementById("minutes");
const hour = new Date().getHours() % 12;
const minute = new Date().getMinutes();
hoursElement.setAttribute("transform", `rotate(${(360 / 12) * hour})`);
minutesElement.setAttribute("transform", `rotate(${(360 / 60) * minute})`);
});
最终效果:
