Mau*_*man 3 javascript svg attributes class function
<script type="text/ecmascript">
<![CDATA[
function setCoordinates(circle) {
var centerX = Math.round(Math.random() * 1000);
var centerY = Math.round(Math.random() * 1000);
circle.setAttribute("cx",centerX);
circle.setAttribute("cy",centerY);
}
]]>
</script>
<circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
<circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
<circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
<circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
<circle class="circles" cx="500" cy="500" r="25" fill="white" filter="url(#f1)" />
<script type="text/ecmascript">
<![CDATA[
setCoordinates(document.getElementsByClassName("circles"));
]]>
</script>
Run Code Online (Sandbox Code Playgroud)
这根本没有效果.但是,当我使用"getElementByID"并为圆圈分配ID时,它工作正常.(歌剧)
document.getElementsByClassName 返回元素集合,因此您需要迭代结果:
var elements = document.getElementsByClassName('circles');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
setCoordinates(element);
}
Run Code Online (Sandbox Code Playgroud)
如果您的代码无法正常运行,请检查您的JS控制台.你应该看到像这样的错误Object has no method 'setAttribute'.