0

我刚刚开始了一个小项目,用 jQuery 用 svg 测试动画,并从动态创建 rect 开始。但是,下面的代码有问题,因为即使我可以在 Inspector 中看到创建的 svg 元素,它们也不会在浏览器中看到。

为什么会这样,我可以改变什么来使矩形被看到?我已经在 Chrome、Firefox 和 Safari 中尝试过代码。

jsFiddle:http: //jsfiddle.net/JFACW/

js:

$(document).ready(function() {

    var NR_OF_FLAKES = 100,
               flake = $('.flake'),
                   x = flake.attr('x'),
                   y = flake.attr('y'),
                 svg = $('#svg');

    for(var i = 0; i < NR_OF_FLAKES; i++) {

        var xPos = randomize('width'),
            yPos = randomize('height');

        $('svg').append('<rect class="flake" width="5" height="5" x=' + xPos + ' y=' + yPos + '/>');
    }

    flake.attr('x');

    var height = $(window).height();

    function randomize(direction) {

        if (direction == 'width')
            direction = $(window).width();
        else
            direction = $(window).height();

        var rand = Math.floor((Math.random() * direction) + 1);

        return rand;
    }
});

html:

...
<body>
    <div id="box2">
        <svg id="svg" xmlns="http://www.w3.org/2000/svg" height="1600" version="1.1"></svg>
    </div>
</body>
...

CSS:

rect.flake {
    fill: rgb(255,205,0);
}
4

2 回答 2

2

只需抛弃 jQuery 并使用纯 JavaScript:

var NR_OF_FLAKES = 100,
             svg = document.querySelector('svg'),
           xmlns = "http://www.w3.org/2000/svg";

for(var i = 0; i < NR_OF_FLAKES; i++) {

   var xPos = Math.random()*window.innerWidth,
       yPos = Math.random()*window.innerHeight,
      flake = document.createElementNS(xmlns, "rect");

  flake.setAttribute("width", 5);
  flake.setAttribute("height", 5);
  flake.setAttribute("x", xPos);
  flake.setAttribute("y", yPos);
  flake.setAttribute("class", "flake");
  svg.appendChild(flake);
}

​</p>

http://jsfiddle.net/PAxyx/

于 2012-11-30T23:58:05.713 回答
1

这是jquery 的 append 的副本,不适用于 svg 元素?

SVG 没有innerHTML,因此.append不起作用。有关详细信息,请参阅链接的问题。

编辑:这可能不是全部真相。jQuery 似乎附加rect了不在 SVG 命名空间中的元素,但它们必须如此。

于 2012-11-30T23:33:41.607 回答