[英]Intercepting anchor href on an SVG
在这个沙箱中,我有一个带有 iFrame 的反应应用程序示例,它加载 HTML 文件并向其添加单击事件侦听器。
原因是在点击时检测href
并采取相应措施。 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
获取带有以下代码段的href
let target = event.target! as HTMLAnchorElement;
const link = isHyperlink(target) ? target : closestATag(target);
if (!link) return;
const theHREF = link.href;
对于第一个<a>
标签, href
正确且带有主机名(ig http://localhost:3000/items/1234)
对于 SVG 中的<a>
标记,link.href 返回SVGAnimatedString:{baseVal:string, animVal:string}
并使用link.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
不包含主机名。
感谢@Frederic Brüning,我的方案专门用于处理所有锚链接。
所以 SVG 中的 a 标签不需要xlink:href="xxx"
而只需要href="xxx"
那么getAttributeNS
不需要命名空间。 getAttributeNS('','href')
) 为任何<a>
标签返回href
(确切的字符串值)
然后附加原点将解决我的问题
theUrl = `${window.location.origin}${link.getAttributeNS('','href')}`
您可以在锚标签中的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.