使用object標籤嵌入跨域SVG內容文檔
P粉393030917
P粉393030917 2023-10-31 18:04:21
0
1
555

擁有一個包含外部域資料的SVG 是否“合法”,即(data="//da86ge957603k.cloudfront.net/rails/grafitti_logo-f4e8238a87c979c0cf5b41481c982b71.svg"),然後將物件載入到contentdocument 屬性存取該物件的SVG DOM?當 SVG 位於本地域時,我可以執行此操作,但每當我嘗試在其他地方託管 SVG 時,我都會收到“this.contentDocument 為空”錯誤。我也嘗試過 getSVGDocument() 。我找不到任何地方說這是一個跨域安全性問題,據我所知,對於用於 SVG 的物件標籤來說,這應該是允許的(我沒有使用 iFrame)。我很感謝您抽出時間來幫助我。下面是我用來嵌入物件和綁定並嘗試存取 DOM 的程式碼(正如我所說,當 SVG 位於本地域時,這會起作用)。

<object id="gangstergraffiti" type="image/svg+xml" data="<%= image_url("grafitti_logo.svg") %>">Gangster</object>

$("#gangstergraffiti").each(function() {
  this.addEventLi stener('load', svgGangsterGraffitiReady, false);
});

function svgGangsterGraffitiReady(){
  var graffitistrokes = this.contentDocument.getElementsByClassName('graffiti');
  for (var i = 0; i < graffitistrokes.length; i++) {
    graffitistrokes[i].setAttribute("stroke", "white");
    graffitistrokes[i].setAttribute("fill", "white");
  }
}


#
P粉393030917
P粉393030917

全部回覆(1)
P粉466643318

w3c 對此進行了記錄。在此處了解物件標籤的詳細資訊 除非透過 CORS,否則您無法跨網域存取 標記的資料。

MDN 上有一個更具可讀性的精煉要解決這個問題,您需要在遠端網站上啟用 CORS(如果可以的話)。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!