这是我的HTML文件(需要jQuery,并在Firefox中启用HTML5:config)

<!DOCTYPE html>

<html>
    <head>
        <script type="text/javascript" src="js/jquery/jquery-1.4.2.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                    $('svg').append("<rect x='100px' y='0px' height='100px' width='100px' fill='red' />");
            })
        </script>
    </head>
    <body>
        <svg viewbox="0 0 300px 600px">
            <rect x='0px' y='0px' height='100px' width='100px' fill='blue' />
        </svg>
    </body>
</html>

问题在于,加载此页面时我看不到红色矩形。在燃烧中,红色矩形广场就像黑暗。

有帮助吗?

解决方案

因此,这似乎是一个名称空间问题,以下代码有效

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="js/jquery/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                    rect = document.createElementNS('http://www.w3.org/2000/svg', "rect");
                    rect.setAttribute("x", "100");
                    rect.setAttribute("y", "0");
                    rect.setAttribute("width", "100");
                    rect.setAttribute("height", "100");
                    rect.setAttribute("fill", "red");
                    $('svg').append(rect);
            })
        </script>
    </head>
    <body>
        <svg viewbox="0 0 200 100" width="200px" height="100px">
            <rect x='0px' y='0px' height='100px' width='100px' fill='blue' />
        </svg>
    </body>
</html>

其他提示

首先,您错过了像这样实现的HTML5 Doctype

<!DOCTYPE html>

在文档的顶部。

然后,您需要准备好添加文档!

$(document).ready(function(){
    //The code here runs when the document is fully loaded into the DOM.
    //Create a blank rect, add its attributes
    the_box = $("<rect/>")
      .attr('x','100px').attr('y','0px')
      .attr('height','100px').attr('width','100px')
      .attr('fill','red');

      //Append the jQuery variable to the selector.
      $('svg[viewbox]').append(the_box);
});

去吧。

有点晚,但是您可以使用jQuery添加名称空间,而是可以将其添加为属性 <svg> 标签:

<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 300px 600px">
  ...
</svg>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top