2011-10-18 19 views
2

更改SVG圖像代碼我需要一種方法來改變圖像的寬度和高度,一個SVG內,基於設備的定向,使用Javascript(或ECMAScript中,在SVG內側)。基於iPad的取向用JavaScript

我使用此代碼,但它不影響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屬性溢出與媒體查詢來實現這種效果(長的故事)相結合。

+0

是否調用它幫助之前宣佈的功能? –

+0

你能澄清一下發生了什麼嗎? 'detectOrientation'被調用了嗎?你是否進入了正確的if語句分支? (順便說一句,爲簡潔起見,您可能想在這裏使用'switch')。getElementById是否返回正確的對象?設置屬性後,它們會發生變化(在DOM中),但是您看不到屏幕上的效果? – Phrogz

+0

Phrogz的回答有助於清除一些問題,但即使在此之後,元素也不會受到影響......也許js無法到達svg內部。 – pagelab

回答

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

+0

謝謝,Phrogz,你的建議解決了與原始JS的問題。但是de SVG中的「image」元素還沒有受到影響,請看:http://bit.ly/mSBDhq。如果我在SVG代碼之外使用常規img標籤,那麼一切都很好。但圖像元素沒有運氣。大概是因爲SVG有自己的命名空間,但我不知道如何JS代碼與它集成... – pagelab

+0

@pagelab我沒有一個iPad來測試這一點,但在Chrome中的JS功能是沒有得到調用。看看編輯我的問題,證明它應該工作,如果JS被調用。 – Phrogz

+0

是的。我嘗試了幾種沒有運氣的調用方法。看不到爲什麼它不起作用的功能。 – pagelab