SVG/PNG扩展开关 [英] SVG/PNG extension switch
问题描述
是否可以在我的网站上使用SVG图片,并且如果浏览器/设备不支持,请将扩展名切换为png?有更好的方法吗?
Is there a way to use SVG images on my site and if browsers/devices do not support it, switch the extension to png? Is there a better way to do this?
注意:我正在使用<img>
标记和Modernizr.
Note: I am using the <img>
tag and Modernizr.
这是我的代码,可以动态弹出图像.
Here is my code that spits out the images dynamically.
<?php $attachments = attachments_get_attachments(); ?>
<?php if( function_exists( 'attachments_get_attachments' ) ) {
$attachments = attachments_get_attachments();
$total_attachments = count( $attachments ); if( $total_attachments ) : ?><?php for( $i=0; $i<$total_attachments; $i++ ) : ?>
<img src="<?php echo $attachments[$i]['location']; ?>" alt="<?php echo $attachments[$i]['title']; ?>" class="full" />
<?php endfor; ?><?php endif; ?><?php } ?>
输出以下内容:
<img src="http://mysiteurl.net/image.png" alt="Image Title" class="full wp-image-287" />
Outputs the following:
<img src="http://mysiteurl.net/image.png" alt="Image Title" class="full wp-image-287" />
推荐答案
我想您可以测试是否支持svg
,如果不支持,则遍历图像标记并将其src路径设置为.png
.此示例尚未经过测试,但这可能是朝着正确方向迈出的一步.
I suppose you could test if svg
is supported, and if not loop through your image tags and set their src path to .png
. This example hasn't been tested, but it may be a step in the right direction.
if(!Modernizr.svg){
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++){
var src = images[i].src.split(".");
images[i].src = src[0] + ".png";
}
}
如果使用jQuery,则可能会发生以下情况:
If jQuery is an option, then something like this may be possible:
if(!Modernizr.svg){
$("img").each(function(){
var src = this.src.split(".");
this.src = src[0] + ".png";
});
}
编辑
您还可以考虑研究 Modernizr-Server .这样,您可以在遍历图像并附加适当的扩展名时测试svg.
You may also consider looking into Modernizr-Server. This way you can test for svg while you're looping through the images and append the appropriate extension.
if ($modernizr->svg) {
...
} elseif ($modernizr->canvas) {
...
}
这篇关于SVG/PNG扩展开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!