我正试图根据这篇post-document.getElementById操作SVG文件,结果为null,其中将SVG移动到object标记和下面是我的文件。
index.html
<body>
<object data="../svg/barplot.svg" alt='bar-graph' type="image/svg+xml" id="barplot" width="800"
height="800">
</object>
</body>
script.js
window.addEventListener("load", function () {
var barplot = document.getElementById("barplot");
console.log(barplot);
var svgDoc = barplot.contentDocument;
console.log(svgDoc);
当我使用VS Code live server
时,svgDoc
的输出是SVG文件本身,一切都很好。
实时服务器(条形图(
<object data="../svg/barplot.svg" alt="bar-graph" type="image/svg+xml" id="barplot" width="800" height="800">
</object>
实时服务器(svgDoc(
#document
<svg>
svg content
</svg>
但是,如果我在终端中使用open index.html
,并在浏览器中从文件系统打开HTML文件,则svgDoc
的控制台输出为空。
Open index.html
(条形图(
<object data="../svg/barplot.svg" alt="bar-graph" type="image/svg+xml" id="barplot" width="800" height="800">
</object>
Open index.html
(svgDoc(
null
为了将来的开发,我必须使用open index.html
方法。有人能帮我解决这个问题吗?感谢
在本地和使用服务器打开网站有其区别
在本地,由于受到CORS的影响,您可以做什么或访问什么确实受到限制
这个案子似乎就是其中之一
您无法访问由文件系统提供服务的文档XMLHttpRequest
或Fetch
API等也受到限制,您将无法使用这些请求本地文件。或者获取在画布上绘制的图像的图像数据。
使用Live服务器打开意味着您在";实时服务器";(你的机器(。
当您打开index.html
时,您只是在查看静态html页面,而没有查看项目中的其他文件。这就是为什么您的svg元素显示为null
。