SVG - getElementsByClassName

时间:2013-01-19 13:51:43

标签: javascript class function svg attributes

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

这根本没有效果。但是,当我使用“getElementByID”并为圆圈分配ID时,它工作正常。 (Opera)的

1 个答案:

答案 0 :(得分:6)

document.getElementsByClassName返回元素集合,因此您需要迭代结果:

var elements = document.getElementsByClassName('circles');

for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    setCoordinates(element);
}

如果您的代码无法正常运行,请检查您的JS控制台。您应该会看到Object has no method 'setAttribute'等错误。