我在我的项目中使用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。
svg没有z指数。但是svg根据元素在DOM中的位置来确定它们的最上面。因此,您可以删除Object并将其放置到svg的末尾,使其成为“最后渲染”元素。然后将其呈现为视觉上的“最顶层”。
使用jQuery:
function moveUp(thisObject){
thisObject.appendTo(thisObject.parents('svg>g'));
}
用法:
moveUp($('#myTopElement'));
使用D3.js:
d3.selection.prototype.moveUp = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
用法:
myTopElement.moveUp();
如前所述,svg按顺序呈现,(目前)不考虑z-index。也许只是把特定的元素发送到它的父元素的底部,这样它就会最后呈现。
function bringToTop(targetElement){
// put the element at the bottom of its parent
let parent = targetElement.parentNode;
parent.appendChild(targetElement);
}
// then just pass through the element you wish to bring to the top
bringToTop(document.getElementById("one"));
为我工作。
更新
如果您有一个嵌套的SVG,其中包含组,则需要将项目从其parentNode中取出。
function bringToTopofSVG(targetElement){
let parent = targetElement.ownerSVGElement;
parent.appendChild(targetElement);
}
SVG的一个很好的特性是每个元素都包含它的位置,而不管它嵌套在哪个组中:+1: