SVG中的Javascript
我创建了一个包含5个多边形的SVG文件,然后我需要嵌入Javascript,这样当鼠标移到上方时,4个多边形的颜色会变为红色,当鼠标移到外面时,颜色会变为绿色。我试着写代码,但没有成功,可能是什么问题?谢谢你的帮助和提示SVG中的Javascript,javascript,svg,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="24
<!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
如您所见,您只需使用CSS中的:hover事件来重新调用必要的元素。并将它们设置为默认颜色(绿色),当用户未悬停时,该颜色将生效。您有各种错误
changeColor
的函数,函数必须具有唯一的名称color
为元素着色,而是使用fill
(和stroke
)id
值必须是唯一的,您可能希望将id
替换为class
,然后使用getElementsByClassName
而不是getElementById
。如果你这样做,你将需要处理不止一个元素。我还没有完成那部分,你应该自己试试看,这样你就能明白发生了什么document.getElementById(“test”).onmouseover=function(){changeColor()};
函数changeColor(){
document.getElementById(“测试”).style.fill=“红色”;
}
document.getElementById(“test”).onmouseout=function(){changeColor2()};
函数changeColor2(){
document.getElementById(“测试”).style.fill=“绿色”;
}
您不能重复使用同一个ID。您需要使用一个类,并通过使用for循环和.length
对每个类进行迭代,将侦听器应用于这两个类。对于onmouseover
和onmouseout
你也必须有不同的行为,我是Javascrip新手,你能给我举个例子吗?你有不止一个bug。我看到它可以工作(运行代码片段),但是,在我做了所有更改之后,它仍然不能工作。我还试图编写与您的代码完全相同的代码(用于测试),但它不起作用。这是怎么可能的,我的意思是代码在运行代码片段时确实工作得很好,但是为什么在我的浏览器中运行SVG文件时它不工作。我认为StackOverflow是最佳实践,而不是完成任务。我不会选择做JS要求你做的事情,因为JS在性能上是低效的。
svg:hover .recolor {
fill: red;
}