我想实现一个工具提示。最简单的想法是当悬停在一个圆上时显示一个矩形。我怎样才能做到这一点?
我不想要的是在没有精确悬停在圆上时显示矩形。
请检查示例: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/