且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在html javascript函数里面调用svg javascript函数

更新时间:2022-12-16 21:44:36

var object = document.getElementById(test)会让你获得对象元素,但直到对象加载完毕才能调用它。一旦你有了,你可以使用object.contentDocument来处理嵌入式svg文档。

 < html> 
< body>
< script>
函数f(){
var svg = document.getElementById('test');
svg.contentDocument.fillCircle('state2');
}
< / script>
< / body>
< / html>


I have a SVG document where three circles are drawn:

<?xml version="1.0"?>
<svg width="450" height="80" xmlns="http://www.w3.org/2000/svg">
    <script>
    document.fillCircle = function(id) {
        var circles = document.getElementsByTagName('circle'),
            circle  = document.getElementById(id);

        [].forEach.call(circles, function(circle) {
            circle.setAttribute('fill','#ffffff');
        });

        circle.setAttribute('fill', '#000000');
    }
    </script>
    <g>
        <line y1="35" x1="35" y2="35" x2="375" stroke-width="3" stroke="#000000"/>
        <circle id="state1" r="30" cy="35" cx="35"  stroke-width="3" stroke="#000000" fill="#ffffff" onclick="fillCircle(this.id);"/>
        <circle id="state2" r="30" cy="35" cx="205" stroke-width="3" stroke="#000000" fill="#ffffff" onclick="fillCircle(this.id);"/>
        <circle id="state3" r="30" cy="35" cx="375" stroke-width="3" stroke="#000000" fill="#ffffff" onclick="fillCircle(this.id);"/>
    </g>
</svg>

For testing purposes I have the onclick="" method, but actually this document is an object in my html document:

<object id="test" data="test-vector.svg" width="100px" height="100px"></object>

I have a dataset and these three circles show the "progress" of every item. I regularly update the JSON set by pulling the new list from the server. For every item changed, I want to update the filled circle.

I would like to update the svg based on some javascript. However, I can't make it to get into the DOM of the SVG. I do not really care if the fillCircle() is inside the svg or not and if I have to use <embed>, <object> or something else, but this kind of javascript does not work for me.

<html>
<body>
    <object id="test" data="test-vector.svg"></object>
    <script>
        var svg = document.getElementById('test');
        console.log(svg);
        svg.fillCircle('state2');
    </script>
</body>
</html>

I tried several things I found on SO, like this one and this one, but whatever I test, the exception is always:

Uncaught TypeError: Object #<HTMLObjectElement> has no method 'fillCircle'

var object = document.getElementById("test") will get you the object element but you can't call that till the object has loaded. Once you have that you can use object.contentDocument to do things with the embedded svg document.

<html>
<body>
    <object id="test" data="test-vector.svg" onload="f()" ></object>
    <script>
        function f() {
            var svg = document.getElementById('test');
            svg.contentDocument.fillCircle('state2');
        }
    </script>
</body>
</html>