getSVGDocument在FireFox和Chrome中返回null

时间:2014-03-20 10:02:37

标签: javascript svg

getSVGDocument是否已损坏?过时了吗?

因为当我"跑步"以下内容:

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>SVG Embedded - Chapter 07</title>
  <link rel="stylesheet" href="../bootstrap/css/bootstrap.css">
  <link rel="stylesheet" href="../assets/style.css">
  <style>
    body { margin: 1em; }
    svg { border: 1px solid silver; }
    rect, text { fill: white; }
    circle { fill: black; }
  </style>
</head>
<body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" height="200" width="300">
<rect width="100%" height="100%" fill="black" />
<circle cx="150" cy="100" r="80" fill="white" />
<text x="150" y="125" font-size="60" text-anchor="middle">SVG</text>
</svg>
<embed src="../assets/svg.svg"></embed>
<object data="../assets/svg.svg"></object>
<script>
document.addEventListener('DOMContentLoaded',function() {
  'use strict';
var rects = document.querySelectorAll('svg'),
      embed = document.querySelector('embed').getSVGDocument();
console.log(rects.length);
  console.log(embed,embed.childNodes.length);
},false);
</script>
</body>
</html>

然后等待所有3个SVG显示(已加载和),并在控制台内输入:document.getElementsByTagName('embed')[0].getSVGDocument()它返回null

可在此处下载整页(包含文件): https://github.com/stopsatgreen/modernwebbook/blob/master/Code%20Examples/Chapter%2007/svg-embedded.html

注意:我将尝试在JS Bin中运行该页面。

修改

问题可能是这个吗? SVG not working when access on localhost. Why?

如果是,如何在不配置(本地)网络服务器的情况下修复它?

2 个答案:

答案 0 :(得分:2)

不推荐使用getSVGDocument()方法。建议的方法是使用contentDocument属性。

See here

答案 1 :(得分:0)

找到解决这个问题的方法,这是一个与安全相关的问题。

浏览器

首先关闭所有正在运行的chrome实例。然后使用命令行标志启动Chrome可执行文件:

chrome --allow-file-access-from-files

在Windows上,最简单的可能是创建一个特殊的快捷方式,它添加了标记(右键单击快捷方式 - &gt;属性 - &gt;目标)。

火狐

转到about:config 找到security.fileuri.strict_origin_policy参数 将其设置为false

到达那里:https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally