簡體   English   中英

jQuery選擇里面的SVG錨元素<object>標簽

[英]jQuery select SVG anchor elements inside <object> tag

我在使用 SVG 內置的錨元素(顯示為<object> )時遇到了很多麻煩。 我正在嘗試使用 jQuery 定位對象中的錨元素,以在單擊時切換其各自的內容。

如果您看一下我的示例,我的 SVG 中內置了 3 個鏈接(它們的綠色比其他鏈接更淺)。 我使用 InkScape 創建了我的 SVG 圖像,並且在鏈接的淺綠色區域上只是具有 href 屬性的形狀分別等於“#operable-shades”、“#gutters-downspouts”和“#gable-pediments”。

隨着我的 SVG 在我的頁面上很好地顯示(使用<object>標簽),當將鼠標懸停在我創建的鏈接上時,我會得到原始對象數據 URL,並在其末尾附加了我指定的錨點(例如“https:// example.com/wp-content/uploads/GHB_Interface-v0.1.svg#gable-pediments') 當我希望它是 'https://example.com/#gable-pediments'。

 <script type="text/javascript"> jQuery(document).ready(function($) { $('.ghb_toggle').hide() $('a[href^="#"]').on('click', function(event) { var target = $(this).attr('href'); $(target).toggle(); }); }); </script>
 .ghb_toggle { display:none; }
 <object type="image/svg+xml" data="https://example.com/wp-content/uploads/test.svg" width="500" height="400"></object> <div id="gable-pediments" class="ghb_toggle"> <p>Content 1</p> </div> <div id="gutters-downspouts" class="ghb_toggle"> <p>Content 2</p> </div> <div id="operable-shades" class="ghb_toggle"> <p>Content 3</p> </div>

我如何修改我的 jQuery 以便能夠成功地與我的<object>錨元素交互以隱藏/顯示具有唯一標識符的相應內容?

要定位加載在<object><iframe>中的 svg 文檔的內容,您需要將正確的 Document 上下文傳遞給 jQuery:您可以從嵌入元素的.contentDocument屬性訪問的上下文。

請注意,這要求 svg 文檔以同源方式加載,這在 StackSnippets 的空源幀中是不可能的,所以這里是一個實時 plnkr

$( "object" ).on( "load", (evt) => {
  const svg_doc = this.contentDocument;
  $( "a[href]", svg_doc ) // second argument is context
    .on( 'click', (evt) => {
      // add your listener here
    } );
};

另請注意,在您的 svg 中,您定義了xlink:href屬性,而不僅僅是href ,因此您的 jQuery 選擇器應該是'a[xlink\\\\:href^="#"]'


但是,如果您的目標是將 svg 中的錨點設置為相對於其他基本 URL 而不是加載文檔的基本 URL,那么您不需要所有這些,您只需在開頭插入一個 HTML <base>元素您的 svg 文檔和所有相關 URL 都將使用它。
將現場演示視為plnkr和更復雜的片段:

 // To be able to embed it in a StackSnippet (directly in this answer), // we need to generate the file in memory from JS // you don't need it const svg_content = ` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="300" > <!-- we must declare it in the HTML namespace --> <base xmlns="http://www.w3.org/1999/xhtml" href="https://google.com" /> <a href="#foo-bar"> <rect fill="green" x="10" y="10" width="30" height="30" /> </a> </svg> `; const svg_blob = new Blob( [ svg_content ], { type: "image/svg+xml" } ); const svg_url = URL.createObjectURL( svg_blob ); document.querySelector( "object" ).data = svg_url;
 <object></object>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM