我应该使用<img>, <object>,或<embed>加载SVG文件到页面的方式类似于加载jpg, gif或png?
每一个代码是什么,以确保它工作得尽可能好?(在我的研究中,我看到了包括mimetype或指向备用SVG渲染器的参考,但没有看到一个良好的艺术状态参考)。
假设我正在使用Modernizr检查SVG支持,并退回到不支持SVG的浏览器(可能使用普通的<img>标记进行替换)。
我应该使用<img>, <object>,或<embed>加载SVG文件到页面的方式类似于加载jpg, gif或png?
每一个代码是什么,以确保它工作得尽可能好?(在我的研究中,我看到了包括mimetype或指向备用SVG渲染器的参考,但没有看到一个良好的艺术状态参考)。
假设我正在使用Modernizr检查SVG支持,并退回到不支持SVG的浏览器(可能使用普通的<img>标记进行替换)。
当前回答
根据个人经验,我建议在image tag中通过src加载svg文件,如果一个页面上有很多svg图标或动态追加,会变慢,性能变差
<img src="./file.svg"/> is better performance than
<div><svg>.....</svg></div>
但是如果你想在hover中指定CSS样式,你必须使用embed
其他回答
我可以推荐SVG Primer(由W3C发布),它涵盖了这个主题:http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_in_HTML
如果你使用<object>,那么你可以免费得到光栅回退*:
<object data="your.svg" type="image/svg+xml">
<img src="yourfallback.jpg" />
</object>
*)好吧,不是完全免费的,因为有些浏览器下载这两种资源,看看Larry下面的建议如何解决这个问题。
2014年更新:
If you want a non-interactive svg, use <img> with script fallbacks to png version (for older IE and android < 3). One clean and simple way to do that: <img src="your.svg" onerror="this.src='your.png'">. This will behave much like a GIF image, and if your browser supports declarative animations (SMIL) then those will play. If you want an interactive svg, use either <iframe> or <object>. If you need to provide older browsers the ability to use an svg plugin, then use <embed>. For svg in css background-image and similar properties, modernizr is one choice for switching to fallback images, another is depending on multiple backgrounds to do it automatically: div { background-image: url(fallback.png); background-image: url(your.svg), none; } Note: the multiple backgrounds strategy doesn't work on Android 2.3 because it supports multiple backgrounds but not svg.
另外一个不错的阅读是这篇关于svg后退的博文。
在大多数情况下,我建议使用<object>标记来显示SVG图像。这感觉有点不自然,但如果你想提供动态效果,这是最可靠的方法。
对于没有交互的图像,可以使用<img>标记或CSS背景。
内联svg或iframe是一些项目的可能选项,但最好避免<embed>
但如果你想玩SVG之类的东西
改变颜色 调整路径 旋转svg
选择嵌入的那个
<svg>
<g>
<path> </path>
</g>
</svg>
对我来说,一个简单的替代方法是将svg代码插入到div中。这个简单的例子使用javascript来操作div innerHTML。
SVG = '< SVG height=150>'; Svg += '<rect height=100% fill=green /><circle cx=150 cy=75 r=60 fill=yellow />'; svg+= '<text x=150 y=95 font-size=60 text-anchor=中间填充=红色>IIIIIII</text></svg>'; document.all.d1.innerHTML = svg; < span style=" font - family:宋体;" > < / div > <人力资源>
最好的选择是在不同的设备上使用SVG图像:)
<img src="your-svg-image.svg" alt="Your Logo Alt" onerror="this.src='your-alternative-image.png'">
从IE9和以上版本,你可以在普通的IMG标签中使用SVG ..
https://caniuse.com/svg-img
<img src="/static/image.svg">