Dra*_*mos 5 html javascript svg cross-domain angularjs
在我的 Angular 应用程序中,我希望能够<object>使用 JavaScript 或 Angular jqLite选择标记的嵌入 SVG 元素。
通常,要执行此操作,必须编写类似于以下内容的内容:
// 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);
Run Code Online (Sandbox Code Playgroud)
在我的控制台中,objElement返回完整<object>的<svg>元素及其内容(假设 data 属性包含完整的 base64 数据字符串 (b64))。
<object id="svgObject" data="b64" type="image/svg+xml">
#document
<svg>
</svg>
</object>
Run Code Online (Sandbox Code Playgroud)
然而,getSVGDocument()返回null和contentDocument返回
#document
<html>
<head></head>
<body></body>
<html>
Run Code Online (Sandbox Code Playgroud)
为什么我无法检索 SVG 元素?如何正确获取 SVG 元素?我已经查看了很多文章,但我无法获得<svg>元素。这可能与跨域策略有关吗?
document.querySelector("svg")即使 SVG 已明确加载到 DOM 中,我也无法使用类似的方法来选择 SVG 。原来我需要这样做:
var obj = document.querySelector("object");
var svg = obj.contentDocument.querySelector("svg");
Run Code Online (Sandbox Code Playgroud)
显然主文档和子文档之间存在边界,您必须使用contentDocument.