为了账号安全,请及时绑定邮箱和手机立即绑定

尝试使用 onclick 事件更改 svg 的颜色。它说它无法指定颜色,因为它的定义不足

尝试使用 onclick 事件更改 svg 的颜色。它说它无法指定颜色,因为它的定义不足

素胚勾勒不出你 2023-10-24 16:01:56
这是我的 svg 文件,它只是我正在练习的一张脸<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"         viewBox="0 0 720 720" style="enable-background:new 0 0 720 720;" xml:space="preserve">    <g id="skin">        <circle class="skin" cx="364.42" cy="383" r="278"/>    </g>    <g id="mouth">        <path class="mouth" d="M172.92,383c127.67,0,255.33,0,383,0c0,105.05-86.45,191.5-191.5,191.5S172.92,488.05,172.92,383z"/>    </g>    <g id="hair">        <path id = "hair" class = "hair" d="M107.4,276.86c-2.76-50.59,10.76-81.24,24.2-100.13C189.57,95.31,331.92,112,341.92,57.91            c2.04-11.03-2.07-21.46-6.93-29.61c18.47-6.31,81.92-25.39,151.28,3.28c94.59,39.09,121.88,137.21,127.56,160.84            c7.93,32.98,7.18,61.32,5.46,79.42c-38.79-64.73-78.17-85.57-107.42-92.42c-43.32-10.15-60.72,11.26-139.64,11.71            c-67.77,0.39-78.13-15.27-119.49-10.14C216.75,185.45,165.19,204.69,107.4,276.86z"/>    </g>    <g id="eyes">        <g>            <circle class = "eyes" cx="251.17" cy="271.25" r="52.4"/>            <circle class = "eyes" cx="477.67" cy="271.25" r="52.4"/>        </g>    </g>    </svg>我正在尝试使用按钮和 onclick 事件将头发更改为蓝色:    <button class="blueButton" onclick="hair.style.fill='blue';"></button>它不会改变颜色,所以我想知道是否有人知道我哪里出了问题......谢谢你!
查看完整描述

2 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

您不能只引用头发元素。相反,调用 document.getElementById('hair') 来获取它。

<button class="blueButton" onclick="document.getElementById('hair').style.fill='blue';">Button</button>

这是一个小提琴,您可以在https://jsfiddle.net/679nLv3p/中看到它的工作原理


查看完整回答
反对 回复 2023-10-24
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

您有两个具有相同 id 的 SVG 对象hair。删除第一组。


<g>

    <path id = "hair" class = "hair" d="M107.4,276.86c-2.76-50.59,10.76-81.24,24.2-100.13C189.57,95.31,331.92,112,341.92,57.91

        c2.04-11.03-2.07-21.46-6.93-29.61c18.47-6.31,81.92-25.39,151.28,3.28c94.59,39.09,121.88,137.21,127.56,160.84

        c7.93,32.98,7.18,61.32,5.46,79.42c-38.79-64.73-78.17-85.57-107.42-92.42c-43.32-10.15-60.72,11.26-139.64,11.71

        c-67.77,0.39-78.13-15.27-119.49-10.14C216.75,185.45,165.19,204.69,107.4,276.86z"/>

</g>

工作jsbin 示例


查看完整回答
反对 回复 2023-10-24
  • 2 回答
  • 0 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信