我在我的项目中使用svg圆圈,像这样,
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 120">
<g>
<g id="one">
<circle fill="green" cx="100" cy="105" r="20" />
</g>
<g id="two">
<circle fill="orange" cx="100" cy="95" r="20" />
</g>
</g>
</svg>
我在g标签中使用z索引来显示第一个元素。在我的项目中,我只需要使用z-index值,但我不能使用我的svg元素的z-index。我在谷歌上搜了很多,但没有找到相关的东西。
所以请帮助我在我的svg中使用z-index。
这里是DEMO。
这是关于z-index和svg搜索的顶级谷歌结果。看完所有的答案后,有些答案很好,但我还是很困惑。
因此,对于像我这样的新手来说,这是目前的总结,9年后的2022年。
svg不能用z指数。
在svg中,z-index由元素在文档中出现的顺序定义。
如果你想要一些东西出现在顶部,或更接近用户,最后绘制或插入它之前。源
SVG 2可以支持z-index,但可能永远不会出现
SVG 2是一个实现这些功能和其他功能的提议,但它面临着永远无法向前发展的风险。
SVG 2于2016年进入候选推荐阶段,并于2018年进行了修订,最新草案于2021年6月8日发布。源
然而,它并没有得到很多的支持,很少有人在做这件事。所以不要屏住呼吸等这个消息。
你可以使用D3,但可能不应该
通常用于可视化数据的D3通过绑定你的z-index,然后排序来支持z-index,但它是一个大而复杂的库,如果你只是想让某个SVG出现在堆栈顶部,它可能不是最好的选择。
我们已经到了2019年,SVG仍然不支持z-index。
您可以在Mozilla的SVG2支持站点上看到z-index的状态-未实现。
你也可以在网站Bug 360148“支持SVG元素上的'z-index'属性”(报告:12年前)上看到。
但在SVG中有3种设置方法:
与element.appendChild(孩子);
parentNode。方法(newNode referenceNode);
targetElement。insertAdjacentElement (positionStr newElement);(IE不支持SVG)
交互式演示示例
这三个函数。
var state = 0,
index = 100;
document.onclick = function(e)
{
if(e.target.getAttribute('class') == 'clickable')
{
var parent = e.target.parentNode;
if(state == 0)
parent.appendChild(e.target);
else if(state == 1)
parent.insertBefore(e.target, null); //null - adds it on the end
else if(state == 2)
parent.insertAdjacentElement('beforeend', e.target);
else
e.target.style.zIndex = index++;
}
};
if(!document.querySelector('svg').insertAdjacentElement)
{
var label = document.querySelectorAll('label')[2];
label.setAttribute('disabled','disabled');
label.style.color = '#aaa';
label.style.background = '#eee';
label.style.cursor = 'not-allowed';
label.title = 'This function is not supported in SVG for your browser.';
}
label{background:#cef;padding:5px;cursor:pointer}
.clickable{cursor:pointer}
With:
<label><input type="radio" name="check" onclick="state=0" checked/>appendChild()</label>
<label><input type="radio" name="check" onclick="state=1"/>insertBefore()</label><br><br>
<label><input type="radio" name="check" onclick="state=2"/>insertAdjacentElement()</label>
<label><input type="radio" name="check" onclick="state=3"/>Try it with z-index</label>
<br>
<svg width="150" height="150" viewBox="0 0 150 150">
<g stroke="none">
<rect id="i1" class="clickable" x="10" y="10" width="50" height="50" fill="#80f"/>
<rect id="i2" class="clickable" x="40" y="40" width="50" height="50" fill="#8f0"/>
<rect id="i3" class="clickable" x="70" y="70" width="50" height="50" fill="#08f"/>
</g>
</svg>