2017-07-28 46 views
0

我的頁面上有一個粘滯頁腳,但是如果啓用JavaScript以確保SVG圖像在懸停時變色,則SVG文件不會顯示在Chrome中。刪除javascript會導致Chrome加載圖像。經過javascript腳本後,Chrome瀏覽器中沒有顯示SVG圖像

我無法重新創建的jsfiddle的效果,但這裏的代碼: https://jsfiddle.net/r9szd060/

這是JavaScript代碼:

$(document).ready(function() { 
    $('img[src$=".svg"]').each(function() { 
     var $img = jQuery(this); 
     var imgURL = $img.attr('src'); 
     var attributes = $img.prop("attributes"); 

     $.get(imgURL, function (data) { 
      // Get the SVG tag, ignore the rest 
      var $svg = jQuery(data).find('svg'); 

      // Remove any invalid XML tags 
      $svg = $svg.removeAttr('xmlns:a'); 

      // Loop through IMG attributes and apply on SVG 
      $.each(attributes, function() { 
       $svg.attr(this.name, this.value); 
      }); 

      // Replace IMG with SVG 
      $img.replaceWith($svg); 
     }, 'xml'); 
    }); 
}); 

我使用嵌入標籤,而不是試圖img標籤,但不會改變chrome中的行爲。 Firefox(桌面+ iOS + Android)可以很好地處理SVG圖像,就像Safari(桌面+ iOS)一樣。 SVG圖像在桌面上的Chrome和Android上的Chrome上消失。奇怪的是,在iOS上的鉻確實工作...

我認爲這與SVG通過JavaScript處理的方式以及SVG如何保存有關,但是我不太熟悉javascript來拾取在問題上。我讀過chrome,有時候SVG文件存在一些問題?我不知道如何上傳SVG文件,以便你可以看到,但是如果有人能告訴我如何傳遞相關信息(例如,在Illustrator中打開的文件),我將把它添加到這篇文章:) 。

有誰知道這個問題是什麼以及我如何解決它?

+0

jQuery是不包含在你的小提琴?! – Superdrac

+0

腳本在那裏,我查過了。不知道它的jQuery或JavaScript,但。就像我說的,我不是很擅長,哈哈。 – Lisa

回答

1

你不能使用CSS來設計任何SVG,你必須在它上面設置一個屬性,寬度。這就是爲什麼你沒有看到他們在頁面上,每個SVG把他的真實大小(大約600像素)。

$(document).ready(function() { 
    $('img[src$=".svg"]').each(function() { 
     var $img = jQuery(this); 
     var imgURL = $img.attr('src'); 
     var attributes = $img.prop("attributes"); 

     $.get(imgURL, function (data) { 
      // Get the SVG tag, ignore the rest 
      var $svg = jQuery(data).find('svg'); 

      // Remove any invalid XML tags 
      $svg = $svg.removeAttr('xmlns:a'); 

      // Loop through IMG attributes and apply on SVG 
      $.each(attributes, function() { 
       $svg.attr(this.name, this.value); 
      }); 

      //Add width on newly created svg 
      $svg.attr('width', '30'); 

      // Replace IMG with SVG 
      $img.replaceWith($svg); 
     }, 'xml'); 
    }); 
}); 
+0

我使用的圖像較小(我想我保存了30x30或類似的東西)。也就是說,爲什麼它在除Chrome之外的每個瀏覽器中都能正常工作,如果屬性丟失了?我測試了你的代碼,它工作,所以我會接受這個答案:)。仍然對瀏覽器的差異感到好奇。 – Lisa

+0

這是一個很好的問題,我在Mozilla和Chrome上獲得了同樣的行爲。它只是不可能適用於svg:( – Superdrac

+0

但我應用css到一個SVG圖像,它也工作。'舊'代碼和新答覆的代碼。在懸停它改變圖像的顏色。每個瀏覽器除外):-) – Lisa

相關問題