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

这是我的 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>

它不会改变颜色,所以我想知道是否有人知道我哪里出了问题......


谢谢你!


素胚勾勒不出你
浏览 68回答 2
2回答

哈士奇WWW

您不能只引用头发元素。相反,调用 document.getElementById('hair') 来获取它。<button&nbsp;class="blueButton"&nbsp;onclick="document.getElementById('hair').style.fill='blue';">Button</button>这是一个小提琴,您可以在https://jsfiddle.net/679nLv3p/中看到它的工作原理

慕雪6442864

您有两个具有相同 id 的 SVG 对象hair。删除第一组。<g>&nbsp; &nbsp; <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&nbsp; &nbsp; &nbsp; &nbsp; 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&nbsp; &nbsp; &nbsp; &nbsp; 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&nbsp; &nbsp; &nbsp; &nbsp; 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 示例
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5