我应该使用<img>, <object>,或<embed>加载SVG文件到页面的方式类似于加载jpg, gif或png?

每一个代码是什么,以确保它工作得尽可能好?(在我的研究中,我看到了包括mimetype或指向备用SVG渲染器的参考,但没有看到一个良好的艺术状态参考)。

假设我正在使用Modernizr检查SVG支持,并退回到不支持SVG的浏览器(可能使用普通的<img>标记进行替换)。


当前回答

对我来说,一个简单的替代方法是将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 > <人力资源>

其他回答

尽管w3schools不推荐<embed>标签,它是唯一让我的svg混合模式和蒙版在Chrome中工作的东西:

<embed src="logo.svg" style="width:100%; height:180px" type="image/svg+xml" />

而Firefox则很好

<svg style="width:100%">
    <use xlink:href="logo.svg#logo"></use>
</svg>

Chrome did not render the gradient: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="146" version="1.1"> <title>digicraft punchcard logo</title> <defs> <linearGradient id="punchcard-gradient" x1="100%" y1="50%" x2="0%" y2="50%"> <stop offset="0%" style="stop-color:rgb(128,128,128);stop-opacity:0" /> <stop offset="100%" style="stop-color:rgb(69,69,69);stop-opacity:1" /> </linearGradient> <pattern id="punchcard-pattern-v" x="0" y="0" width="21" height="21" patternUnits="userSpaceOnUse"> <rect x="0" y="0" width="20" height="20" fill="skyblue" onClick="mClick(this)" /> </pattern> <pattern id="punchcard-pattern-h" x="0" y="0" width="21" height="145" patternUnits="userSpaceOnUse"> <rect x="0" y="0" width="21" height="20" fill="skyblue" /> <rect x="0" y="20" width="20" height="84" fill="url(#punchcard-pattern-v)" /> <rect x="0" y="105" width="20" height="20" fill="skyblue" /> <rect x="0" y="126" width="21" height="20" fill="skyblue" /> </pattern> <mask id="punchcard-mask" width="10" height="100%"> <rect width="100%" height="146" fill="url(#punchcard-pattern-h)" /> </mask> </defs> <rect x="0" y="0" width="100%" height="159" fill="url(#punchcard-gradient)" mask="url(#punchcard-mask)" /> </svg>

两个浏览器中的<object>和<img>也是如此。

从IE9和以上版本,你可以在普通的IMG标签中使用SVG ..

https://caniuse.com/svg-img

<img src="/static/image.svg">

最好的选择是在不同的设备上使用SVG图像:)

<img src="your-svg-image.svg" alt="Your Logo Alt" onerror="this.src='your-alternative-image.png'">

使用srcset

目前大多数浏览器都支持srcset属性,它允许为不同的用户指定不同的图像。例如,您可以使用它的1x和2x像素密度,浏览器将选择正确的文件。

在这种情况下,如果您在srcset中指定了SVG,而浏览器不支持它,它将退回到src。

<img src="logo.png" srcset="logo.svg" alt="My logo">

与其他解决方案相比,这种方法有几个优点:

它不依赖于任何奇怪的黑客或脚本 它很简单 您仍然可以包含alt文本 支持srcset的浏览器应该知道如何处理它,以便它只下载所需的文件。

<object>和<embed>有一个有趣的属性:它们可以从外部文档获得对SVG文档的引用(将同源策略考虑在内)。然后可以使用引用来动画SVG,更改其样式表等。

鉴于

<object id="svg1" data="/static/image.svg" type="image/svg+xml"></object>

你可以这样做

document.getElementById("svg1").addEventListener("load", function() {
    var doc = this.getSVGDocument();
    var rect = doc.querySelector("rect"); // suppose our image contains a <rect>
    rect.setAttribute("fill", "green");
});