为了账号安全,请及时绑定邮箱和手机立即绑定

jQuery 选择 <object> 标签内的 SVG 锚点元素

jQuery 选择 <object> 标签内的 SVG 锚点元素

吃鸡游戏 2023-05-25 17:27:11
我在使用我的 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>以隐藏/显示具有唯一标识符的相应内容?
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

<object>要定位在, 或中加载的 svg 文档的内容<iframe>,您需要将正确的文档上下文传递给 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,那么您不需要所有这些,您可以简单地在 svg 文档的开头插入一个 HTML<base>元素并且所有相对 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>


查看完整回答
反对 回复 2023-05-25
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信