2017-01-22 80 views
0

我試圖顯示和svg內的外部圖像,然後在按鈕單擊上更改它。我無法展示背景,也無法讓它改變。顯示和更改外部SVG背景圖像

這裏是我的小提琴:

https://jsfiddle.net/bsp9601z/

<head><meta http-equiv="X-UA-Compatible" content="IE=edge"> 
</head> 
<div id="slider"></div> 
<button onclick="go()">change background</button> 
<g id="backgroundImage"> 
    <image width="100%" height="100%" xlink:href="http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg" /></g> 


<svg width="792pt" height="612pt" viewBox="0 0 792 612" enable-background="new 0 0 792 612" 
    version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > 

</svg> 
</svg> 



function go(){ 

     var im = document.getElementById('backgroundImage'); 
       im.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',  'http://demo.elmanawy.info/moraco/layout1/assets/images/portfolio/8.jpg'); 
       im.setAttributeNS('http://www.w3.org/1999/xlink','width', "100%"); 
       im.setAttributeNS('http://www.w3.org/1999/xlink','height', "100%"); 

} 
+0

我對svg不太瞭解,但好像你沒有正確使用 https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g 沒有這樣的事情標籤,只有。而且你還有額外的收盤價 – myfashionhub

+0

@myfashionhub https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image – guest271314

回答

0

你缺少<svg>標籤並選擇<g>而非<image>

<button onclick="go()">change background</button> 
 
<svg> 
 
<g id="backgroundImage"> 
 
    <image width="100%" height="100%" xlink:href="http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg" /> 
 
</g> 
 
</svg> 
 
<script> 
 
    function go() { 
 
    var im = document.getElementById('backgroundImage').querySelector("image"); 
 
    im.setAttributeNS('http://www.w3.org/1999/xlink' 
 
    , 'xlink:href' 
 
    , 'http://demo.elmanawy.info/moraco/layout1/assets/images/portfolio/8.jpg'); 
 
} 
 

 
</script>

+0

@RobertLongson好的。由於'width'和'height'不會從初始值改變,所以不需要將屬性重新設置爲相同的值。查看更新的帖子。 – guest271314