我是靠谱客的博主 平常仙人掌,这篇文章主要介绍如何用js动态插入svg?如何在svg中在插入Dom元素,现在分享给大家,希望可以做个参考。

如何用js动态插入svg?如何在svg中在插入Dom元素?

最近遇到了这个问题,于是好好研究了一番。有这么一篇文章,可以关注。解释的很清楚。

http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element


粘出里面的关键代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
    <svg id="s" xmlns="http://www.w3.org/2000/svg"/>
    <script type="text/javascript">
        function makeSVG(tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }

        var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
        document.getElementById('s').appendChild(circle);
        circle.οnmοusedοwn= function() {
            alert('hello');
        };
    </script>
</body></html>



<script type="text/javascript"><![CDATA[
    function parseSVG(s) {
        var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
        var frag= document.createDocumentFragment();
        while (div.firstChild.firstChild)
            frag.appendChild(div.firstChild.firstChild);
        return frag;
    }

    document.getElementById('s').appendChild(parseSVG(
        '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert('hello');"/>'
    ));
]]></script>
大致意思是,svg是xml格式的语言,就算在dom里看上去已经加上了,但是还是不能被识别出来的。

只能曲线救国。

最后

以上就是平常仙人掌最近收集整理的关于如何用js动态插入svg?如何在svg中在插入Dom元素的全部内容,更多相关如何用js动态插入svg内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部