我们不仅可以通过 JavaScript 操作 SVG,还可以为 SVG 的各个部分分配事件监听器。在这里,通过点击红色按钮,我们可以打开或关闭灯光。能力是无限的。您甚至可以用 SVG 和 JavaScript 创建一个全功能的游戏。
<svg class="lights" width="200" height="200" viewBox="-100 -100 200 200">
<script>
window.addEventListener("DOMContentLoaded", () => {
const button = document.getElementById("button");
let lightsOn = false;
button.addEventListener("click", () => {
const bulbs = document.querySelectorAll(".b");
bulbs[0].setAttribute("fill", lightsOn ? "white" : "#FFC05B");
bulbs[1].setAttribute("fill", lightsOn ? "white" : "#F86285");
bulbs[2].setAttribute("fill", lightsOn ? "white" : "#03A8A8");
bulbs[3].setAttribute("fill", lightsOn ? "white" : "#748CEF");
lightsOn = !lightsOn;
});
});
</script>
<defs>
<g id="bulb">
<path d="M 0,0 Q 20 25 0 40 Q -20 25 0 0" />
<rect x="-6" y="-1" width="12" height="10" rx="3" fill="#5F4C6C" />
</g>
</defs>
<path d="M -140 -60 Q -70 -50 0 -60 Q 110 -70 110 10" />
<line x1="-70" y1="-15" x2="-70" y2="-55" />
<line x1="30" y1="-25" x2="30" y2="-60" />
<use class="b" href="#bulb" x="-120" y="-45" transform="rotate(5)" />
<use class="b" href="#bulb" x="-70" y="-15" />
<use class="b" href="#bulb" x="-20" y="-57" transform="rotate(-5)" />
<use class="b" href="#bulb" x="30" y="-25" />
<rect x="90" y="10" width="40" height="40" fill="lightgray" />
<circle id="button" cx="110" cy="30" r="15" fill="red" />
</svg>
.lights {
fill: none;
stroke: #5f4c6c;
stroke-width: 2;
}
.lights #button {
cursor: pointer;
}
分享: |