SVG/PNG extension switch

喜夏-厌秋 提交于 2020-01-13 11:34:10

问题


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?

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 } ?>

Outputs the following: <img src="http://mysiteurl.net/image.png" alt="Image Title" class="full wp-image-287" />


回答1:


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";
  }
}

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";
  });
}

EDIT

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) {
    ...
}



回答2:


This is working, filtering only svg file

<script type="text/javascript">
jQuery( document ).ready(function() {
    if(!Modernizr.svg){
      jQuery("img").each(function(){
        var src = this.src;
        if( src.match(/svg$/) ){
            // Replace "svg" by "png"
            this.src = src.slice(0,-3) + 'png'
        }           
      });
    }
});
</script>



回答3:


An alternative is to use a CSS-ony solution for SVG with fallback as described in this answer: https://stackoverflow.com/a/13575068/418711



来源:https://stackoverflow.com/questions/12846852/svg-png-extension-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!