【问题标题】:Can't access SVG contents with javascript无法使用 javascript 访问 SVG 内容
【发布时间】:2020-09-16 23:48:01
【问题描述】:

我在 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 及其所有内容和元素。那为什么它们无法访问?

【问题讨论】:

    标签: javascript html svg dom


    【解决方案1】:

    我通过将文件放在互联网上解决了这个问题(以前它们是离线的)。

    上线后,我可以联系到contentDocument,它不再为空。控制台输出:

    obj.contentDocument = [object XMLDocument]
    

    然后我可以用 javascript 更改 SVG 的内容...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 2010-10-11
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 2014-09-29
      相关资源
      最近更新 更多