SVG/PNG extension switch

戏子无情 提交于 2019-12-05 13:24:49

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

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>
Pau Giner

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

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