SVG 中的 JavaScript

标签 javascript svg

我创建了一个包含 5 个多边形的 SVG 文件,然后我需要嵌入 Javascript,以便当鼠标悬停时,其中 4 个多边形的颜色变为红色,当鼠标移开时,颜色变为绿色。我尝试编写代码,但没有成功,可能是什么问题?感谢您的帮助和提示!

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="26cm" height="24cm" viewBox="0 0 2600 2400" version="1.1" 
  xmlns="http://www.w3.org/2000/svg" 
  xmlns:xlink= "http://www.w3.org/1999/xlink">
<script type="text/javascript">
<![CDATA[

document.getElementById("test").onmouseover = function(){changeColor()};

function changeColor() {
document.getElementById("test").style.color = "red";
}

document.getElementById("test").onmouseout = function(){changeColor()};

function changeColor() {
document.getElementById("test").style.color = "green";
}

]]>
</script>
<circle cx="1600" cy="700" r="600" fill="yellow" stroke="black" stroke-width="3"/>
<ellipse id="test" cx="1300" cy="500" rx="74" ry="120" fill="blue" stroke="black"  stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<ellipse id="test" cx="1850" cy="500" rx="74" ry="120"  fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<rect id="test" x="1510" y="650" width="160" height="160" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<polygon id="test" points="1320,800 1370,1080 1820,1080 1870,800 1820,1000 1370,1000" name="mouth" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/> 

</svg>

最佳答案

对于你正在做的事情,我建议使用纯 CSS。

Here is some working code.

svg:hover .recolor {
    fill: red;     
}

如您所见,您可以使用 CSS 中的 :hover 事件来重新着色必要的元素。并将它们设置为您的默认颜色(绿色),该颜色将在用户未悬停时生效。

关于SVG 中的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833977/

相关文章:

javascript - 将鼠标悬停在链接上时显示图像

javascript - 解决所有错误后,如何使 data-parsley-errors-container ="#element"消失?

javascript - 按顺序收集 AJAX 结果

string - 阻止 R 将尾随空格写入保存的字符串

javascript - anchor 上的 svg 动画

javascript - d3 中的放大镜

javascript - 使用 JavaScript 更改所有未单击圆圈的 SVG 圆圈的 CSS 属性

javascript - 异步函数与javascript中的类

javascript - 带有 SVG 数据 URI 的 img 将不会在 Firefox 中显示

javascript - 如何获取剪贴板数据的base64字符串?