我创建了一个包含 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。
svg:hover .recolor {
fill: red;
}
如您所见,您可以使用 CSS 中的 :hover 事件来重新着色必要的元素。并将它们设置为您的默认颜色(绿色),该颜色将在用户未悬停时生效。
关于SVG 中的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833977/