【问题标题】:access SVG from Javascript does not work [duplicate]从Javascript访问SVG不起作用[重复]
【发布时间】:2015-07-28 18:56:03
【问题描述】:

我一直在关注有关使用 Javascript 访问 SVG 元素的示例,但我无法让它工作。这段代码有什么问题?

Javascript:

var objTag = document.getElementById('esc-seconds-1s');
objTag.addEventListener('load', function() {
    var svgDoc = objTag.contentDocument;
    var cc3 = svgDoc.getElementById('cc3');
    cc3.setAttribute('fill', 'red');
}, false);

我收到以下控制台错误:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

我认为错误是有点错过领先。该错误来自 contentDocument 行,所以我不认为这是因为相同的来源政策。另外,我在 SVG 文件中没有任何 xlink 行。这是我的 SVG 的顶部:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

SVG显示正常,为什么objTag.contentDocument调用失败?

html:

<object class="esc-seven-segment" id="esc-seconds-1s"
     type="image/svg+xml" data="images/seven-segment-digit.svg"></object>

谢谢,

-安德烈斯

【问题讨论】:

标签: javascript svg


【解决方案1】:

您是否使用 Chrome 并处理本地文件(即file://)?

Using iframe with local files in Chrome

要么运行本地网络服务器 (http://localhost/),要么尝试使用其他浏览器进行测试。

【讨论】:

  • 宾果游戏,就是这样。感谢 Paul 的回复 - 清除了错误。
猜你喜欢
  • 2017-09-04
  • 1970-01-01
  • 2014-04-22
  • 2010-12-22
  • 2013-11-19
  • 1970-01-01
  • 2016-10-23
  • 2017-05-03
  • 1970-01-01
相关资源
最近更新 更多