繁体   English   中英

如何添加<svg>随后是<polygon>使用浏览器的 DOM 的 javascript 元素包括 HTML 中的属性?</polygon></svg>

[英]How to add a <svg> and subsequently a <polygon> element including attributes in HTML with javascript using the brower's DOM?

所以,这是代码:

       <!doctype html>
        <html>
        <head>
        <script type="text/javascript">

        function stars() {

        var svg = document.createElement("svg");
        var polygon = document.createElement("polygon");


        polygon.setAttribute("style","width:70px;height:70px;")
        // A star with the vector points.
        polygon.setAttribute("points","10,1 4,19.8 19,7.8 1,7.8 16,19.8"); 
        // More properties.
        polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;")
        // Put in the parent element.
        svg.appendChild(polygon);
        // Then again, put this parent element in an existing element, that is: "div".
        document.getElementById("littlediv").appendChild(svg);

    }

        </script>
        <style type="text/css">


        #littlediv
        {
        position:absolute;
        width:100px;
        height:100px;
        }

        svg
        {
        position:absolute;
        height:100px;
        width:100px;
        }

        polygon
        {
        position:absolute;
        height:100px;
        width:100px;
        }

        </style>
        </head>

        <body onload="stars()">

        <div id="littlediv">
        <!-- Here is where the created elements with it's attributes will append. -->
        </div>

        </body>
        </html>

加载页面时,事件侦听器调用函数stars() 然后在函数内部,创建 html 元素svg和随后的polygon ,将polygon元素附加到svg ,然后再次将svg元素附加到现有元素,即: div

现在,元素和伴随的style属性将被整齐地插入到该元素的div标签中。 但是,在检查时,元素和属性声明不会显示在页面中。 所以在 CSS 中,我将所有元素的尺寸预设为 100x100 像素。

当然你可以复制/粘贴代码,以.html 后缀保存并检查。

我是不是做了什么蠢事? 为什么元素不显示?

改变:

    var svg = document.createElement("svg");
    var polygon = document.createElement("polygon");

到:

    var xmlns = "http://www.w3.org/2000/svg";

    var svg = document.createElementNS(xmlns, "svg");
    var polygon = document.createElementNS(xmlns, "polygon");

主要区别是使用 createElementNS() 而不是 createElement()

有关原因的更多详细信息...... createElement 与 createElementNS

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM