Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击时用外部图像替换SVG元素_Javascript_Html_Svg_Onclick - Fatal编程技术网

Javascript 单击时用外部图像替换SVG元素

Javascript 单击时用外部图像替换SVG元素,javascript,html,svg,onclick,Javascript,Html,Svg,Onclick,我目前有一个由9个40×40px的蓝色正方形组成的网格,使用HTML设置为SVG: <svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" width="200" height="200" > <rect id="topLeft" x="20" y="20" width="40" height="40" fill="blue"/> <rect id="topC

我目前有一个由9个40×40px的蓝色正方形组成的网格,使用HTML设置为SVG:

<svg version="1.1"
   baseProfile="full"
   xmlns="http://www.w3.org/2000/svg"
   width="200" height="200" >
<rect id="topLeft" x="20" y="20" width="40" height="40" fill="blue"/>
<rect id="topCenter" x="80" y="20" width="40" height="40" fill="blue"/>
<rect id="topRight" x="140" y="20" width="40" height="40" fill="blue"/>

<rect id="midLeft" x="20" y="80" width="40" height="40" fill="blue"/>
<rect id="midCenter" x="80" y="80" width="40" height="40" fill="blue"/>
<rect id="midRight" x="140" y="80" width="40" height="40" fill="blue"/>

<rect id="bottomLeft" x="20" y="140" width="40" height="40" fill="blue"/>
<rect id="bottomCenter" x="80" y="140" width="40" height="40" fill="blue"/>
<rect id="bottomRight" x="140" y="140" width="40" height="40" fill="blue"/>

</svg>
我还有另一个40 x 40px image.svg文件。当用户单击九个蓝色方块中的一个时,我希望该方块被此文件替换,然后将该方块从可单击选项中删除,直到所有方块都被单击并替换为另一个图像,此时将出现一个弹出窗口。到目前为止,我有这样的想法:

while (squares.length > 0){
    for (square in squares){
        square.onclick = function(){
            // replace square with image.svg;
            availableSquares.splice(square,1);
    alert("You clicked them all!")
        }
    }
}
我已经看过了,但是我对SVG和交互式事件还不熟悉,所以它们对我都不是很有帮助

每个矩形应该是它自己的SVG,还是一个SVG带有不同的元素标记

我应该像这样创建替换图像作为元素吗

var image = document.createElement("svg")

至少作为一个编程注意事项,不使用九个单独的变量,而只使用document.querySelectorAllsvg rect的结果要有效得多。因为您知道,…[0]是左上角,…[5]是中间,…[8]是右下角。谢谢,我认为有一种更精简的方法可以做到这一点。关于替换SVG有什么想法吗?您可以使用常规的DOM API来执行类似element.parentNode.replaceChild、element的操作,用图像元素替换rect元素。
var image = document.createElement("svg")