我有一个 SVG 文档,其中绘制了三个圆圈:
<?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>
出于测试目的,我有 onclick=""
方法,但实际上这个文档是我的 html 文档中的一个对象:
<object id="test" data="test-vector.svg" width="100px" height="100px"></object>
我有一个数据集,这三个圆圈显示了每个项目的“进度”。我通过从服务器中提取新列表来定期更新 JSON 集。对于每个更改的项目,我想更新实心圆圈。
我想根据一些 javascript 更新 svg。但是,我无法进入 SVG 的 DOM。我真的不在乎 fillCircle()
是否在 svg 内,如果我必须使用 <embed>
, <object>
或其他东西,但这种 javascript 对我不起作用。
<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>
我尝试了一些在 SO 上找到的东西,比如 this one和 this one ,但无论我测试什么,异常总是:
Uncaught TypeError: Object #<HTMLObjectElement> has no method 'fillCircle'
最佳答案
var object = document.getElementById("test")
将为您提供对象元素,但在对象加载之前您不能调用它。一旦你有了它,你就可以使用 object.contentDocument 来处理嵌入的 svg 文档。
<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>
关于javascript - 在 html javascript 函数中调用 svg javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784237/