更改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屬性溢出與媒體查詢來實現這種效果(長的故事)相結合。
是否調用它幫助之前宣佈的功能? –
你能澄清一下發生了什麼嗎? 'detectOrientation'被調用了嗎?你是否進入了正確的if語句分支? (順便說一句,爲簡潔起見,您可能想在這裏使用'switch')。getElementById是否返回正確的對象?設置屬性後,它們會發生變化(在DOM中),但是您看不到屏幕上的效果? – Phrogz
Phrogz的回答有助於清除一些問題,但即使在此之後,元素也不會受到影響......也許js無法到達svg內部。 – pagelab