【问题标题】:Is there a way to put an SVG element above an HTML div with an absolute position?有没有办法将 SVG 元素放在具有绝对位置的 HTML div 上方?
【发布时间】:2019-09-08 02:32:35
【问题描述】:

我是 D3.js 的新手,我有一个特定的问题。我正在尝试将一个元素(圆圈)放在具有绝对位置的 HTML div 上方的 SVG 中,我可以在那里做些什么?

我已经尝试放置 z-index,更改位置类型...我认为我的问题在于 SVG,我无法像通常使用常规 HTML 那样应用相同的规则。

看这个例子https://jsfiddle.net/L70yk9f1/13/

div.a {
  width: 400px;
  height: 400px;
  background: lightgrey;
}

div.b {
  width: 200px;
  height: 400px;
  background: lightgreen;
  position: absolute;
  top: 8px;
  left: 400px;
}
<!-- the circle should appear above the green div -->
<div class="a">
  <svg width="400px" height="400px">
    <circle cx="390" cy="100" r="50" x="100" style="stroke: black; fill: yellow;"/>
  </svg>  
</div>
<div class="b"></div>

我正在尝试将黄色圆圈(SVG 中的一个元素)放在绿色 div 上方。

【问题讨论】:

  • b 必须是 a 的子级
  • 没有宽度和/或高度的 svg 元素将采用父元素的宽度。一种方法是给 svg 一个 viewBox 属性,例如 viewBox = "0 0 400 400" 并将其放在绿色 div 中。

标签: javascript html css d3.js svg


【解决方案1】:

我想这就是你想要的......?

div.a {
  width: 100%;
  height: 400px;
  background: lightgrey;
  position:absolute;
}
div.a svg{
    position: absolute;
    z-index: 999999;
    width: 100%;
    height:100%;
}
div.b {
  width: 200px;
  height: 400px;
  background: lightgreen;
  position: absolute;
  top: 8px;
  left: 400px;
}
<!-- the circle should appear above the green div -->
<div class="a">
  <svg>
    <circle cx="390" cy="100" r="50" x="100" style="stroke: black; fill: yellow;"/>
  </svg>  
</div>
<div class="b"></div>

【讨论】:

  • 几乎是因为这样,svg 中的所有元素都会出现在绿色的上方,这个想法只是圆圈,但你给了我其他想法,可能会有不同的方法
  • @JerryMartinez Ho 好的...但是是的,只需很少的改编就可以了。祝你好运:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 2016-03-16
  • 1970-01-01
  • 2021-01-30
相关资源
最近更新 更多