鍍金池/ 問答/室內(nèi)設(shè)計(jì)  HTML/ svg animateMotion通過js動態(tài)添加無效

svg animateMotion通過js動態(tài)添加無效

如果不加載js直接,直接寫在html是正常的。應(yīng)該如何解決?

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="http://code.jquery.com/jquery-1.12.4.js"></script>
    </head>

    <body>
        <div id="map" style="width: 1024px;height:930px;margin: auto;overflow: hidden;">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100%" width="100%">
                <!--             <path fill="none" data-uid="1179" id="motionPath-1179-1" stroke="red" d="M940,190Q880,230 870,220Q860,230 850,230Q840,230 830,230Q820,230 810,220Q810,210 830,230Q810,200 810,190" stroke-width="3"></path>
                <image x="-15" y="-30" width="30" height="60" class="cop" id="cop" style="" href="./cop.gif"></image>
                <animateMotion xlink:href="#cop" class="animate" rotate="auto-reverse" dur="8s" fill="freeze">
                    <mpath xlink:href="#motionPath-1179-1"></mpath>
                </animateMotion> -->
    </svg>
        </div>
    </body>
    <script>
    var drawAnimate = function() {
        var svg = $("svg");

        var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');

        var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        path.setAttribute("fill", "none");
        path.setAttribute("data-uid", 'motionPath-1179-1');
        path.setAttribute("id", 'motionPath-1179-1');
        path.setAttribute("stroke", 'red');
        path.setAttribute("d", "M" + '940,190Q880,230 870,220Q860,230 850,230Q840,230 830,230Q820,230 810,220Q810,210 830,230Q810,200 810,190');
        path.setAttribute("stroke-width", 3);
        $(g).append(path);

        var image = document.createElementNS('http://www.w3.org/2000/svg', 'image');
        image.setAttribute("x", 0);
        image.setAttribute("y", 0);
        image.setAttribute("width", 30);
        image.setAttribute("height", 60);
        image.setAttribute("class", "cop");
        image.setAttribute("id", "cop");
        image.href.baseVal = "./cop.gif"; 
        $(g).append(image);

        var animate = document.createElementNS('http://www.w3.org/2000/svg', 'animateMotion');
        animate.setAttribute("xlink:href", '#cop');
        animate.setAttribute("class", "animate");
        animate.setAttribute("repeatCount","indefinite");
        animate.setAttribute("rotate", "auto-reverse");
        animate.setAttribute("dur", "8s");
        // animate.setAttribute("begin", "click");
        animate.setAttribute("fill", "freeze");

        var mpath = document.createElementNS('http://www.w3.org/2000/svg', 'mpath');
        mpath.setAttribute("xlink:href", '#motionPath-1179-1');

        $(animate).append(mpath);
        $(g).append(animate);
        svg.append(g);
        return g;
    }
    drawAnimate();
    </script>
回答
編輯回答
帥到炸

請問問題解決沒有,我也有同樣的問題 T_T

2018年1月21日 22:22