我在HTML页面上有一个SVG图片。图像加载良好,并且在屏幕上可见。我尝试用js访问它,但是没有运气。最简单的示例:
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick="print();">Print</button>
<object data="drawing.svg" type="image/svg+xml" onload="print();"></object>
</body>
<script>
function print() {
var obj = document.body.getElementsByTagName("object")[0];
console.log("obj = " + obj);
console.log("obj.getSVGDocument() = " + obj.getSVGDocument());
console.log("obj.contentDocument = " + obj.contentDocument);
console.log("obj.firstElementChild = " + obj.firstElementChild);
console.log("obj.childNodes.length = " + obj.childNodes.length);
}
</script>
</html>
尝试在加载后立即访问它,或稍后单击按钮,控制台输出始终为:
obj = [object HTMLObjectElement]
obj.getSVGDocument() = null
obj.contentDocument = null
obj.firstElementChild = null
obj.childNodes.length = 0
我还检查了著名的snippet,但它给了我
Uncaught TypeError: Cannot read property 'getElementById' of null at HTMLObjectElement.<anonymous>
在Chrome和Mozilla Firefox中进行了测试。我想念什么吗?在DOM中可以看到SVG及其所有内容和元素。那么为什么它们无法访问?
答案 0 :(得分:0)
我通过将文件放在Internet上(以前是脱机的)解决了这个问题。
将它们放到网上之后,我可以到达contentDocument
,它不再是null。控制台输出:
obj.contentDocument = [object XMLDocument]
然后我可以使用javascript更改SVG的内容...