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

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

最佳答案

为文本赋予属性 pointer-events: none 以便它被鼠标忽略。

请注意,您不需要 javascript 来执行悬停 CSS:悬停即可。

rect {
    fill: white;
}

rect:hover {
    fill: #c8cace;
}
<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>

关于javascript - 如何将 svg 形状与 svg 文本合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588328/

相关文章:

CSS - 在最后一个 nth-child 动画结束后重复动画

html - 更改选定链接的 BG 颜色

javascript - 如何在 node.js 中导入 font-awesome 以在 react.js 中使用?

javascript - 如何使用文本 anchor : middle in fabric js

jquery - 将元素定位到树上

javascript - 修复桌面上 div 的移动 View

javascript - 在没有 jQuery 的情况下在新选项卡中打开外部链接

javascript - 如何命令 if ( ..) 不执行 setTimeout()

jquery - 修复了平板电脑和手机问题的导航栏

html - IE9-11 @媒体冲突