如何在 HTML 中使用外部 SVG?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28652648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:33:50  来源:igfitidea点击:

How to use external SVG in HTML?

htmlcsssvg

提问by Abdelouahab

I try to make an HTML that references to an SVG file, that SVG file is interractive (CSS hover):

我尝试制作一个引用 SVG 文件的 HTML,该 SVG 文件是交互式的(CSS 悬停):

  1. If I use <img src="algerie.svg">I loose the interactivity.

    SVG displayed as image embedded in an HTML page

  2. If I open this image in a new tab using dev tool, it becomes interactive.

    SVG opened in the browser, showing interactive highlights

  3. If I use:

    <svg viewBox="0 0 512 512">
      <use xlink:href="algerie.svg"></use>
    </svg>
    

    Then nothing is shown, and worse, Chrome or Firefox do not detect the file in the network dev tool.

  1. 如果我使用,<img src="algerie.svg">我会失去交互性。

    SVG 显示为嵌入在 HTML 页面中的图像

  2. 如果我使用开发工具在新选项卡中打开此图像,它将变为交互式。

    在浏览器中打开的 SVG,显示交互式亮点

  3. 如果我使用:

    <svg viewBox="0 0 512 512">
      <use xlink:href="algerie.svg"></use>
    </svg>
    

    然后什么也没有显示,更糟糕的是,Chrome 或 Firefox 无法在网络开发工具中检测到该文件。

回答by NikitaBaksalyar

You should embed the image by using <object>tag:

您应该使用<object>标签嵌入图像:

<object data="algerie.svg" type="image/svg+xml"></object>

Refer to this question for the details: Do I use <img>, <object>, or <embed> for SVG files?

有关详细信息,请参阅此问题:对于 SVG 文件,我使用 <img>、<object> 或 <embed> 吗?