2017-09-23 532 views
-1

我需要一个内嵌SVG图表,该图表具有应该在悬停时触发“工具提示”的“更多信息”图标。见附件。 enter image description here如何在SVG元素悬停时显示工具提示div

我有工具提示div风格,并在其他地方使用,但我也需要它来触发SVG内的信息图标。

我知道我不能在SVG中添加工具提示html,那么还有什么其他选项可用于我?

“图表”是直接从图形程序(本例中为草图)中直接获取的内联SVG。我没有使用像D3或chartjs这样的框架或库。请不要建议使用库或框架,因为它不是一个选项。

相似,所以问题,但他们没有回答我的问题: How to create an SVG "tooltip"-like box?

+0

的foreignObject标签将允许您添加工具提示的HTML SVG。链接答案有什么问题?你目前写了什么代码?需要解决哪些问题? –

+0

要求使用自定义工具提示而不是浏览器内置工具提示 – user1275105

+0

向我们展示您已拥有的代码。你说你有工具提示div。提供一些最小的SVG标记,即[mcve] –

回答

1

这很简单。它只需要几行Javascript。

当我们将鼠标悬停在图标上时,我们定位弹出框并显示它。在mouseout上,我们再次隐藏它。

还要注意图标上的pointer-events="all",它确保即使对于具有不可见填充的位,鼠标也被视为“超过”图标元素。

var myicon = document.getElementById("myicon"); 
 
var mypopup = document.getElementById("mypopup"); 
 

 
myicon.addEventListener("mouseover", showPopup); 
 
myicon.addEventListener("mouseout", hidePopup); 
 

 
function showPopup(evt) { 
 
    var iconPos = myicon.getBoundingClientRect(); 
 
    mypopup.style.left = (iconPos.right + 20) + "px"; 
 
    mypopup.style.top = (window.scrollY + iconPos.top - 60) + "px"; 
 
    mypopup.style.display = "block"; 
 
} 
 

 
function hidePopup(evt) { 
 
    mypopup.style.display = "none"; 
 
}
body { 
 
    background-color: #33333f; 
 
} 
 

 
#mypopup { 
 
    width: 400px; 
 
    padding: 20px; 
 
    font-family: Arial, sans-serif; 
 
    font-size: 10pt; 
 
    background-color: white; 
 
    border-radius: 6px; 
 
    position: absolute; 
 
    display: none; 
 
} 
 

 
#mypopup::before { 
 
    content: ""; 
 
    width: 12px; 
 
    height: 12px; 
 
    transform: rotate(45deg); 
 
    background-color: white; 
 
    position: absolute; 
 
    left: -6px; 
 
    top: 68px; 
 
}
<svg width="400" height="400"> 
 
    <g id="myicon" pointer-events="all"> 
 
    <circle cx="100" cy="150" r="14" fill="none" stroke="gold" stroke-width="2"/> 
 
    <circle cx="100" cy="144" r="2" fill="gold"/> 
 
    <rect x="98.5" y="148" width="3" height="10" fill="gold"/> 
 
    </g> 
 
</svg> 
 

 
<div id="mypopup"> 
 
    <h3>Popup title</h3> 
 
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> 
 
    <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> 
 
</div>

+0

谢谢。 getBoundingClientRect方法是我所需要的。 – user1275105

相关问题