繁体   English   中英

如何选择一个 SVG 元素<object>用 JavaScript 标记?

[英]How to select an SVG element inside an <object> tag with JavaScript?

在我的 Angular 应用程序中,我希望能够使用 JavaScript 或 Angular jqLit​​e 选择<object>标签的嵌入 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);

在我的控制台中, objElement返回带有<svg>元素及其内容的完整<object> (假设 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来弥合鸿沟。

似乎不推荐使用getSVGDocument()。 你尝试过像document.querySelector('object svg')吗?

您看不到该对象的原因是因为您很可能在 DOM 加载之前对其进行了探测。 尝试:

// 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);

objElement.addEventListener('load', doStuff);

function doStuff() {
  console.log(objElement);
  var svgDoc = getSVGDoc(objElement);
  console.log('svgDoc', svgDoc);
}


function getSVGDoc(element) {
  console.log('getting obj');
  try {
    return element.contentDocument;
  } catch (e) {
    try {
      return element.getSVGDocument();
    } catch (e) {
      console.log('SVG unsupported within this browser');
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM