html - 不根据子项自动缩放的 SVG 容器元素

标签 html css svg

我想实现一个工具提示。最简单的想法是当悬停在一个圆上时显示一个矩形。我怎样才能做到这一点?

我不想要的是在没有精确悬停在圆上时显示矩形。

请检查示例:https://codepen.io/EminDurak/pen/JXOVqv

SVG:

<svg width="800px" height="300px" viewBox="0 0 800 300" xmlns="http://www.w3.org/2000/svg">

<g x="282.7416666666667" y="252.6" width="3" height="3" class="tooltip-container">

  <circle cx="200" cy="120" r="20" value="12" class="tooltip-circle"></circle>

  <rect x="50" y="30" width="300" height="80" rx="4" ry="4" r="5" value="12" class="tooltip-box"></rect>

  <text x="100" y="80" style="fill:black">Shouldn't appear when hovered here</text>
  <text  x="150" y="160" style="fill:black">Hover the circle</text>
</g>
</svg>

和CSS(SCSS):

.tooltip-box {
  fill: purple;
  opacity: 0;
  stroke-width: 1px;
}

.tooltip-container {
  &:hover > * {
    opacity: 1 !important;
  }
}

最佳答案

事实证明,这个问题的最佳解决方案是使用 display:none , 而不是 opacity:0 .在写这个问题的时候,我还没有检查哪些 CSS 选择器适用于 SVG;不认为显示会是一个。但确实如此。

所以下面这段代码有效:

<g x="282.7416666666667" y="252.6" width="3" height="3" class="tooltip-container">

  <circle cx="200" cy="120" r="20" value="12" class="tooltip-circle"></circle>

  <rect x="50" y="30" width="300" height="80" rx="4" ry="4" r="5" value="12" class="tooltip-box"></rect>

</g>

和CSS:

.tooltip-box {
  fill: purple;
  opacity: 0;
  stroke-width: 1px;
}

.tooltip-container:hover > .tooltip-box {
  opacity: 1;
}

注意:我放置 <Text> 的原因element 只是为了表明我想做什么。要点是,当一个 svg 元素被设置为 display:none 时, 容器 <g>相应地计算元素的大小,就好像根本没有渲染 svg 元素一样。然后可以将元素设置为 display: block悬停在容器上 <g>并因此能够执行,比方说,工具提示功能。

关于html - 不根据子项自动缩放的 SVG 容器元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36454646/

相关文章:

javascript - 当 ul-li 切换时,数据表会发生变化

html - 在 Groovy 1.7 中使用包含混合内容的 HTML 构建器的正确语法是什么?

JavaScript 按钮。 - 添加/删除类/id 样式 onClick。 - 显示 : none/block

Firefox 不显示数据 URI SVG

javascript - Angular2 中的动态着色图形

html - 表格单元格背景渗入带有圆 Angular 的表格

javascript - 用javascript设置div背景

jquery - 多选下拉菜单 : Custom Checkbox

html - 溢出-x : hidden sets overflow-y to auto/scroll behaviour

fonts - 使用矢量软件(即 inkscape)和 fontforge 创建图标字体?