从 URL 使用 HTML 中的 .svg 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34097191/
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 18:35:48  来源:igfitidea点击:

Using a .svg file in HTML from a URL?

htmlsvg

提问by Albraa

I am trying to use an svg from an external source in my html. Let's say I have this svg: https://upload.wikimedia.org/wikipedia/commons/0/09/America_Online_logo.svg

我正在尝试在我的 html 中使用来自外部源的 svg。假设我有这个 svg:https: //upload.wikimedia.org/wikipedia/commons/0/09/America_Online_logo.svg

I found many ways to do this, including:

我找到了很多方法来做到这一点,包括:

<img src="your.svg"/>?
<object data="your.svg"/>?
<iframe src="your.svg"/>?
<embed src="your.svg"/>?
<div style="background:url(your.svg)">...</div>

But unfortunately, the styling I have to use applies to svg tags. If I use this for example:

但不幸的是,我必须使用的样式适用于 svg 标签。例如,如果我使用它:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">       
<image xlink:href="https://upload.wikimedia.org/wikipedia/commons/0/09/America_Online_logo.svg"/>    
</svg>

It won't show up on my page, I just get an empty white square! Is there anyway I can do this inside svg tags? Thanks!

它不会出现在我的页面上,我只会得到一个空白的白色方块!无论如何我可以在 svg 标签中做到这一点吗?谢谢!

回答by lexith

You have to specify a width and height for your svg to display properly:

您必须为 svg 指定宽度和高度才能正确显示:

<svg width="90" height="90">       
     <image xlink:href="your.svg" src="yourfallback.png" width="90" height="90"/>    
</svg>

Update

更新

You can do this via CSS too of course, but you have to be sure that your <image>tag has width and height set in your CSS if you don't specify the html attributes directly:

当然,您也可以通过 CSS 执行此操作,但是<image>如果您不直接指定 html 属性,则必须确保您的标签在 CSS 中设置了宽度和高度:

 svg {
      width: 150px;
      height: 150px;
 }

 image {
      width: 100px;
      height: 100px;
 }

This will set the size of your actual image (the svg) to 100px * 100px, but has a "wrapper" of 150px. Regarding to your comment to your original question, maybe that's why you don't see your image, because you dont have set a width / height and only styles which apply to your wrapping element (<svg>)

这会将您的实际图像(svg)的大小设置为100px * 100px,但具有150px. 关于您对原始问题的评论,也许这就是您看不到图像的原因,因为您没有设置宽度/高度,并且只有适用于您的包装元素的样式 ( <svg>)

Example Fiddle: https://jsfiddle.net/7334vrmq/

小提琴示例:https: //jsfiddle.net/7334vrmq/

Hope this helps.

希望这可以帮助。