简体   繁体   English

SVG容器元素不会根据子元素自动缩放

[英]SVG container element that doesn't auto-scale according to children

I want to implement a tooltip. 我想实现一个工具提示。 The idea in its most simplicity is to show a rectangular, when hovered on a circle. 最简单的想法是将鼠标悬停在圆形上时显示一个矩形。 How can I achieve that? 我该如何实现?

What I do not want is to show the rectangular when not hovered precisely on the circle. 我不想要的是显示未正确悬停在圆上的矩形。

Please check the example: https://codepen.io/EminDurak/pen/JXOVqv 请检查示例: https : //codepen.io/EminDurak/pen/JXOVqv

SVG: 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>

And the CSS (SCSS): 和CSS(SCSS):

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

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

So it turns out that the best solution to this problem is using display:none , instead of opacity:0 . 因此,事实证明,解决此问题的最佳方法是使用display:none而不是opacity:0 At the time of writing the question I had not checked which css selectors work for SVG; 在撰写本文时,我还没有检查过哪些CSS选择器适用于SVG; didn't think display would be one. 没想到显示器会是一个。 But it is. 但它是。

So this code below works: 所以下面的代码可以工作:

<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>

and css: 和CSS:

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

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

Note: The reason I placed the <Text> element was just to indicate what I was trying to do. 注意:放置<Text>元素的原因只是为了表明我要执行的操作。 The main point is that when an svg element is set to display:none , the container <g> element's size is computed accordingly, so as if the svg element is not rendered at all. 要点是,当将svg元素设置为display:none ,将相应地计算容器<g>元素的大小,就好像根本不呈现svg元素一样。 Then one can set the element to display: block on hovered to container <g> and consequentially be able to exercise, let's say, a tooltip function. 然后,可以将元素设置为display: block悬停在容器<g> ,因此可以执行工具提示功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM