【问题标题】:Intercepting anchor href on an SVG在 SVG 上拦截锚点 href
【发布时间】:2021-05-01 11:25:32
【问题描述】:

this sandbox 我有一个带有 iFrame 的 react 应用示例,它加载 HTML 文件并向其添加点击事件侦听器。

原因是在点击时检测hrefs 并采取相应措施。 HTML 还包含一个 SVG 部分,我在获取带有主机名的 href 时遇到问题。

    <div>
      <a href="/items/1234"> Link outside of SVG</a>
    </div>
    <div>
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid meet" viewBox="0 0 756 1315">
        <a href="/items/1234" id="huvud">
          <path
            d="M342...14.07Z"
            id="myID"
            fill="#5fe4"
            opacity="50"
          ></path>
        </a>
      </svg>
    </div>

MouseEvent 获取带有以下sn-p 的href

let target = event.target! as HTMLAnchorElement;
    const link = isHyperlink(target) ? target : closestATag(target);
    if (!link) return;
    const theHREF = link.href;

对于第一个&lt;a&gt; 标签,href 是正确的并且带有主机名(例如 http://localhost:3000/items/1234)

对于 SVG 中的 &lt;a&gt; 标记,link.href 返回 SVGAnimatedString:{baseVal:string, animVal:string},使用 link.getAttributeNS('http://www.w3.org/1999/xlink', 'href') 获取 href 不包含主机名。

【问题讨论】:

    标签: javascript reactjs svg mouseevent href


    【解决方案1】:

    感谢@Frederic Brüning,我的方案专门用于处理所有锚链接。

    xlink:href is depricated

    所以SVG中的a标签不需要xlink:href="xxx"而只需要href="xxx"

    那么getAttributeNS 不需要命名空间。 getAttributeNS('','href') 为任何 &lt;a&gt; 标签返回 href(确切的字符串值)

    然后附加原点将解决我的问题

    theUrl = `${window.location.origin}${link.getAttributeNS('','href')}`
    

    【讨论】:

      【解决方案2】:

      您可以在锚标签中的 href 属性之前添加 xlink: 的 uri。也许然后像这样添加当前位置:

      window.location.hostname + link.getAttributeNS("http://www.w3.org/1999/xlink", "href");
      
      
      <a xlink:href="/items/1234" id="huvud">
            <path
              d="M342...14.07Z"
              id="myID"
              fill="#5fe4"
              opacity="50"
            ></path>
      </a>
      

      也可以从属性的节点元素中获取baseURI。

      let node = link.getAttributeNodeNS("http://www.w3.org/1999/xlink", "href")
      
      node.baseURI + node.value
      

      【讨论】:

      • 感谢您的提示。仅供参考getAttributeNodeNS 不适用于 Safari
      猜你喜欢
      • 2021-02-04
      • 2018-06-30
      • 1970-01-01
      • 2018-06-18
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      相关资源
      最近更新 更多