SVG图像不会在iOS8上调整大小

时间:2016-01-14 15:53:30

标签: html css svg

我有带PNG后备的SVG图片:

 <svg width=64 height=64>
  <image xlink:href="gender-male.svg"
   src="gender-male.png" width="100%" height="100%"> </image>
 </svg>

当我通过CSS为外部SVG设置不同的大小时,它会在所有浏览器上正确调整内部图像的大小:

 svg.small {
   width: 50px;
   height: 50px;
 }

但是在iOS8上,内部图像不会缩放并保持原始大小:

SVG on iOS8

演示:jsfiddle

我在SVG标题中尝试了各种更改:

<svg preserveAspectRatio="xMidYMin"
     x="0px" y="0px" width="283px" height="283px" 
     viewBox="0 0 283.5 283.5" 
     enable-background="new 0 0 283.5 283.5" xml:space="preserve">

另一张图片:

<svg preserveAspectRatio="xMidYMin meet"
     x="0px" y="0px"
     viewBox="0 0 283.5 283.5" 
     enable-background="new 0 0 283.5 283.5" xml:space="preserve">

还有用于图像的各种CSS方法(max-widthabsolute position等),但似乎没有任何效果。即使setting the size in JS也不起作用。

还有其他想法吗?

1 个答案:

答案 0 :(得分:0)

Solution实际上很简单,但你必须知道问题是什么。

问题是,外部SVG元素是根据其CSS属性调整大小的,但内部IMAGE是基于HTML属性widthheight呈现的

要使其正确渲染,您只需在每次元素的实际大小更改时更改HTML大小属性:

    if ((-1 < navigator.userAgent.indexOf('iPhone')
      || -1 < navigator.userAgent.indexOf('iPad'))
      && window.navigator.userAgent.match(new RegExp('OS ([1-8])_'))) {
     //iOS8 and older cannot correctly resize SVG graphic inside element resized by CSS

        $(window).on('resize.svg-size', function() {
            $('svg').each(function() {
                var me = $(this);

                //if height is set to auto, you may need to fix it first
                me.css('height', me.width() * me.data('ratio'));

                //set HTML attributes to current size defined in CSS
                me.attr('width', me.width());
                me.attr('height', me.height());

                //if there is also another container, fix it as well
                me.parent().height(me.parent().width() * me.data('ratio'));
            });
        });
        //call the handler when the page is loaded
        $(function() { $(window).triggerHandler('resize.svg-size'); });
    } //Fix for gender select size on iOS8 and older

HTML(外部DIV是可选的):

<div class="image-container">    
  <svg width=64 height=64 data-ratio=1><!-- square image -->
      <image xlink:href="gender-male.svg"
             src="gender-male.png" width="100%" height="100%"> </image>
  </svg>
</div>
<div class="image-container">    
  <svg width=100 height=75 data-ratio="0.75"><!-- 4:3 image -->
      <image xlink:href="gender-female.svg"
             src="gender-female.png" width="100%" height="100%"> </image>
  </svg>
</div>