如何将svg形状与svg文本合并

时间:2017-10-05 14:36:23

标签: javascript html css svg

我在尝试将svg文本与svg形状合并时遇到问题。 这是我当前的代码,当我的指针在框中时,白条只变为灰色,但是当它在字母上时,框变回白色。如何使它保持灰色,即使我的鼠标在文本上,直到我将指针移离文本和方框。我已经尝试将这些功能放在<g><a><svg>标签中,但它根本无法工作。

<script>
    function ontop(x){
        x.style.fill = "#c8cace"
    }

    function notOnTop(x){
        x.style.fill = "white"
    }
</script>

    <svg>
    <g>
        <a href="https://google.com" target="_blank" >
        <rect height="50px" width="350px" x="70%" y="14%" fill="white" rx="5px" onmouseenter="ontop(this)" onmouseleave="notOnTop(this)" />
        <text x="72%" y="22%" font-size="20" fill="black" >Google</text>
        </a>
    </g>
    </svg>

2 个答案:

答案 0 :(得分:1)

为文本指定属性pointer-events:none,以便鼠标忽略它。

请注意,您不需要使用javascript来悬停CSS:hover会这样做。

&#13;
&#13;
rect {
    fill: white;
}

rect:hover {
    fill: #c8cace;
}
&#13;
<svg>
    <g>
        <a href="https://google.com" target="_blank" >
        <rect height="50px" width="350px" x="70%" y="14%" rx="5px" />
        <text x="72%" y="22%" font-size="20" fill="black" pointer-events="none">Google</text>
        </a>
    </g>
</svg>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将文字移到矩形后面。并使矩形半透明。

<svg width="5cm" height="4cm" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <script>
    function ontop(x){
        x.style.fill = "#c8cace"
    }

    function notOnTop(x){
        x.style.fill = "white"
    }
  </script>
    <g>
        <a href="https://google.com" target="_blank" >
        <text x="72%" y="22%" font-size="20" fill="black" >Google2</text>
        <rect height="50px" width="350px" x="70%" y="14%" fill="white" rx="5px" opacity="0.5"
        onmouseenter="ontop(this)" onmouseleave="notOnTop(this)"/>
    </a>
    </g>
</svg>

<强> EDIT1

添加了SVG名称空间,使其作为独立的svg文件运行。