WordPress中的内联SVG后备

时间:2016-01-14 00:32:03

标签: javascript wordpress svg

我正在构建一个包含选项面板的WordPress主题。在选项面板中,管理员可以上传将显示在页脚中的图标。

上传图标时,管理员会将SVG和PNG版本上传到媒体上传器(例如icon.svg和icon.png)。

我在前端显示这个图标,如下所示:

<nav>
<?php if( have_rows('footer_icons', 'option') ): ?>
    <ul>
    <?php while( have_rows('footer_icons', 'option') ): the_row();
        // Vars
        $icon = get_sub_field('icon');
    ?>
        <li>
            <img src="<?php echo esc_url($icon); ?>" alt="icon" width="60" height="60">
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>
</nav>

如果浏览器不支持SVG,有没有办法检测并显示内联png后备(icon.png)?我知道Modernizr提供SVG检测,但我看不出它会提供这种级别的支持。

2 个答案:

答案 0 :(得分:1)

我会质疑它是否有必要。浏览器对img标签中使用SVG的支持在全球范围内超过96%。资料来源:http://caniuse.com/#feat=svg-img

如果绝对必要,请将PNG URL作为数据属性添加到img标记,并将源设置为SVG文件。如果不支持SVG图像,则在Modernizr中加载并使用其特征检测将图像的源替换为PNG URL。

示例标记(假定$png_icon已设置):

<img src="<?php echo esc_url( $icon ); ?>" data-png-src="<?php echo esc_url( $png_icon ); ?>" alt="icon" width="60" height="60">

进一步阅读:

https://modernizr.com/docs

http://callmenick.com/post/svg-fallback-with-png(示例#4)

答案 1 :(得分:1)

由于您确实在onerror代码中显示了svg而不是内联问题的标题,因此最简单的方法是使用<img src="https://dl.dropboxusercontent.com/s/b7qcju9ubmdtigj/ball.svg" onerror="this.src='https://dl.dropboxusercontent.com/s/gd7vo53yfrmaqx4/ball.png'"/>事件处理程序:

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;