我如何在 Raphael 或其底层的 SVG 元素创建后重新排序它们?更好的做法是,SVG 中是否存在类似图层的东西?
理想情况下,我希望有两个或更多的图层,可以随时将元素放置在其中;一个背景图层和一个前景图层。如果那不是一个选项,将元素移到前面会很好,将其推到后面在这种特殊情况下会更好。
谢谢!
我如何在 Raphael 或其底层的 SVG 元素创建后重新排序它们?更好的做法是,SVG 中是否存在类似图层的东西?
理想情况下,我希望有两个或更多的图层,可以随时将元素放置在其中;一个背景图层和一个前景图层。如果那不是一个选项,将元素移到前面会很好,将其推到后面在这种特殊情况下会更好。
谢谢!
// move element "on top of" all others within the same grouping
el.parentNode.appendChild(el);
// move element "underneath" all others within the same grouping
el.parentNode.insertBefore(el,el.parentNode.firstChild);
// move element "on top of" all others in the entire document
el.ownerSVGElement.appendChild(el);
// move element "underneath" all others in the entire document
el.ownerSVGElement.appendChild(el,el.ownerSVGElement.firstChild);
在 Raphael 中,使用 toBack()
和 toFront()
更加容易:
raphElement.toBack() // Move this element below/behind all others
raphElement.toFront() // Move this element above/in front of all others
SVG在绘制对象时使用"绘画模型":文档中后出现的项目会在先出现的元素之后(在顶部)绘制。要更改项目的分层,必须使用appendChild
或insertBefore
等方法重新排序DOM中的元素。
您可以在此处查看示例:http://phrogz.net/SVG/drag_under_transformation.xhtml
此示例中元素的重新排序由源代码的第93/94行完成:
el.addEventListener('mousedown',function(e){
el.parentNode.appendChild(el); // move to top
...
},false);
当鼠标按下一个元素时,它会被移动到所有同级元素的最后一个位置,导致它在所有其他元素之上绘制,成为最上层的元素。
SVG 中没有 z-index 属性,后面出现的对象会显示在前面出现的对象之上。因此,您可以将节点移动到树的开头或结尾来满足您的需求。
<g>
(分组)元素是 SVG 中的通用容器,因此它们可以成为图层。只需在组之间移动节点即可实现所需效果。
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1000 1000" width="400" height="400">
<rect x="0" y="0" width="1000" height="1000" fill="black"/>
<defs>
<rect id="a1" x="0" y="0" width="500" height="500" fill="red"/>
<rect id="a2" x="100" y="100" width="500" height="500" fill="blue"/>
</defs>
<g>
<use xlink:href="#a1"/>
<use xlink:href="#a2"/>
<set attributeName="visibility" to="hidden" begin="2s"/>
</g>
<g visibility="hidden">
<use xlink:href="#a2"/>
<use xlink:href="#a1"/>
<set attributeName="visibility" to="visible" begin="2s"/>
</g>
</svg>
el.parentNode.appendChild(el.parentNode.removeChild(el));