【问题标题】:Interactive SVG via HTML object tag通过 HTML 对象标签的交互式 SVG
【发布时间】: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 没有工作(或者至少在某些浏览器中没有),因为我还没有等待 (不仅仅是窗口)加载。请参阅:stackoverflow.com/a/15680844/5285945(我的评论也链接到另一个相关答案)。
  • 感谢您的评论。我也试过&lt;script&gt; var a = document.getElementById("svg"); a.addEventListener("load",function(){ svgDoc = contentDocument; //(also tried getSVGDocument() ) alert(svgDoc); },false); &lt;/script&gt;,但没用。
  • 在您尝试的第一件事中,它需要是 svgDoc = a.contentDocument 而不仅仅是 svgDoc = contentDocument(或者这可能只是一个转录错误?)
  • 抱歉,这是一个转录错误。问题在于将 Chrome 与本地文件一起使用。不过谢谢你的回答!

标签: javascript html svg


【解决方案1】:

当没有设置(本地)服务器时,Chrome 似乎在加载对象时出现问题。

我尝试了 Microsoft Edge /IE 并解决了问题。我可以访问 SVG 文件中的所有元素。

【讨论】:

  • 我认为如果您使用的是 Chrome。因为 Chrome 不允许 xmlhttprequest 请求本地文件。因此它无法加载您的文件,您可以将 --allow-file-access-from-files 添加到 chrome 快捷方式的启动目标命令中。这可以让 xmlhttprequest 加载本地资源
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
相关资源
最近更新 更多