【问题标题】:Can I link two elements in svg such that mousing over one changes an attribute of the other?我可以链接 svg 中的两个元素,以便将鼠标悬停在一个元素上会更改另一个元素的属性吗?
【发布时间】:2021-09-04 03:32:24
【问题描述】:

假设我有 2 个 svg 元素、一个圆圈和一些文本:

<svg version="1.1" width="500" height="500" viewBox="0 0 1500 1500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle cx="1000" cy="1000" r="50" />
    <text x="900" y="900" style="font-size:100px">Test</text>
</svg>

接下来,我希望文本仅在鼠标悬停时出现,我可以这样做:

<svg version="1.1" width="500" height="500" viewBox="0 0 1500 1500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <circle cx="1000" cy="1000" r="50" />
    <text x="900" y="900" style="font-size:100px" opacity="0" onmouseover="evt.target.setAttribute('opacity', '1');" onmouseout="evt.target.setAttribute('opacity', '0');">Test</text>
</svg>

是否可以链接圆圈和文本,以便将鼠标悬停在其中一个上会导致文本变得可见,同时在所有情况下保持圆圈可见?

【问题讨论】:

    标签: xml svg mouseevent mouseover


    【解决方案1】:

    根据 Robert Longson 的有用评论,这是一个 JavaScript 解决方案:

    <svg version="1.1" width="500" height="500" viewBox="0 0 1500 1500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">  
        <circle id="circle" cx="1000" cy="1000" r="50" />
        <text id="text" x="900" y="900" style="font-size:100px" opacity="0">Test</text>
        <script>
            <![CDATA[
                var circle = document.getElementById("circle");
                var text = document.getElementById("text");
                circle.addEventListener("mouseover",function(event){
                    text.setAttribute('opacity',1);
                })
                circle.addEventListener("mouseout",function(event){
                    text.setAttribute('opacity',0);
                })
            ]]>
        </script>
    </svg>
    

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多