如何使用JavaScript在标签内选择SVG元素?

在我的Angular appliation中,我希望能够选择< object>的嵌入式SVG元素.使用 JavaScript或Angular jqLit​​e标记.

通常,要执行此操作,必须编写类似于以下内容的内容:

// Create <object> element of the SVG
var objElement = document.createElement('object');
objElement.setAttribute('type',"image/svg+xml");

// Assume $rootScope.b64 contains the base64 data of the SVG
objElement.setAttribute('data', $rootScope.b64);

// Append the <object> inside the DOM's body
angular.element(document.body).append(objElement);

console.log(objElement);
console.log(objElement.getSVGDocument());
console.log(objElement.contentDocument);

在我的控制台中,objElement返回完整的< object>使用< svg>元素及其内容(假设data属性包含完整的base64数据字符串(b64)).

    <object id="svgObject" data="b64" type="image/svg+xml">
          #document
             <svg>
             </svg>
    </object>

但是,getSVGDocument()返回null并返回contentDocument

    #document
       <html>
          <head></head>
          <body></body>
       <html>

为什么我无法检索SVG元素?如何正确获取SVG元素?我已经查看了很多文章而且我无法获得< svg>元件.这可能与跨省政策有关吗?

最佳答案 我也无法使用诸如document.querySelector(“svg”)之类的东西选择SVG,即使SVG明显加载在DOM中也是如此.原来我需要这样做:

var obj = document.querySelector("object");
var svg = obj.contentDocument.querySelector("svg");

显然主文档和这个子文档之间存在边界,您必须使用contentDocument来弥合鸿沟.

点赞