【发布时间】:2016-09-14 04:07:48
【问题描述】:
我想创建一个交互式 SVG HTML 页面。例如:如果我点击一个矩形,我想显示一个新的 SVG-Image。
因为我的 SVG 文件是独立的,所以我想通过 HTML-Object 标记包含它们。
我已经浏览了一段时间的网络,但我只是无法处理我的 SVG 文件的单个元素来更改它们的属性或添加功能等。
我的 HTML 文件:
<!DOCTYPE html>
<html>
<body>
<object data="svg-test.svg" type="image/svg+xml" id="svg" width="100%" height="100%"></object>
<script>
window.onload=function() {
// Get the Object by ID
var svgObject = document.getElementById("svg");
// Get the SVG document inside the Object tag
var svgDoc = svgObject.contentDocument;
// Get one of the SVG items by ID;
var svgItem = svgDoc.getElementById("svgID");
// Set the colour to something else
svgItem.setAttribute("fill", "lime");
};
</script>
</body>
</html>
SVG 文件:
<svg width="900" height="600" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="100" y="120" width="200" height="350"
style="fill:white;stroke:black;stroke-width:2;fill-opacity:1.0;stroke-opacity:1.0"
id="svgID"/>
</svg>
我也尝试了 getSVGDocument() 而不是使用 contentDocument,但这也没有用。
【问题讨论】:
-
在我的情况下, contentDocument 没有工作(或者至少在某些浏览器中没有),因为我还没有等待
-
感谢您的评论。我也试过
<script> var a = document.getElementById("svg"); a.addEventListener("load",function(){ svgDoc = contentDocument; //(also tried getSVGDocument() ) alert(svgDoc); },false); </script>,但没用。 -
在您尝试的第一件事中,它需要是
svgDoc = a.contentDocument而不仅仅是svgDoc = contentDocument(或者这可能只是一个转录错误?) -
抱歉,这是一个转录错误。问题在于将 Chrome 与本地文件一起使用。不过谢谢你的回答!
标签: javascript html svg