使用JavaScript更改基于iPad方向的SVG图像代码

时间:2011-10-18 14:10:37

标签: javascript ipad svg orientation

我需要一种方法来改变SVG内的图像宽度和高度,基于设备的方向,使用Javascript(或SVAS内的ECMAScript)。

我正在使用此代码,但它不会影响SVG中的图像元素。

// SVG code, inside XHTML file
<svg xmlns="http://www.w3.org/2000/svg" class="birds" height="569px" id="bird01" version="1.1" width="368px" x="0px" xml:space="preserve" xmlns:xlink="http://www.w3.org/1999/xlink" y="0px">
  <g>
    <defs>
      <rect class="crop" height="569" id="SVGID_1_" width="368"></rect>
    </defs>
    <use overflow="visible" xlink:href="#SVGID_1_"></use>
    <g clip-path="url(#SVGID_2_)">
      <image clip-path="url(#SVGID_2_)" height="846" id="bird-img" overflow="visible" width="547" xlink:href="../Images/bird.jpeg"></image>
    </g>
  </g>
</svg>

// JS code, outside file, referenced in head

window.onload = function initialLoad() {
     detectOrientation();
}

detectOrientation();
    window.onorientationchange = detectOrientation;
    function detectOrientation(){
        if(typeof window.onorientationchange != 'undefined'){
            if ( orientation == 0 ) {
                 document.getElementById("bird-img").setAttribute("width", "547").setAttribute("height", "846");
            }
            else if ( orientation == 90 ) {
                 document.getElementById("bird-img").setAttribute("width", "368").setAttribute("height", "568");
            }
            else if ( orientation == -90 ) {
                 document.getElementById("bird-img").setAttribute("width", "368").setAttribute("height", "568");
            }
            else if ( orientation == 180 ) {
                 document.getElementById("bird-img").setAttribute("width", "547").setAttribute("height", "846");
            }
        }
    }

此链接显示测试页面:http://bit.ly/mSBDhq调整窗口大小以查看SVG框更改其大小。我只想在两种情况下(横向和纵向)将图像大小调整为SVG框的宽度。我正在使用CSS媒体查询来完成大部分工作,但SVG图像元素不受CSS的影响,这就是我正在寻找JS解决方案的原因。我很欣赏这一点。

旁注:遗憾的是,在这种情况下,我根本无法使用常规图像标记和CSS属性溢出结合媒体查询来实现这种效果(长篇故事)。

1 个答案:

答案 0 :(得分:0)

请注意setAttribute()不会返回接收者。实际上,它符合规范has no return value。这不是jQuery。

让我们稍微干掉你的功能并同时修复它:

function detectOrientation(){
  if(typeof window.onorientationchange == 'undefined') return;
  var img = document.getElementById('bird-img');
  switch(orientation){
    case 0:
    case 180:
      img.setAttribute('width',547);
      img.setAttribute('height',846);
    break;
    case 90:
    case -90:
      img.setAttribute('width',368);
      img.setAttribute('height',568);
    break;
  }
}

修改:证明代码运行时会影响图片(至少在Chrome中):

http://phrogz.net/tmp/ResizedBird.png