[英]Intercepting anchor href on an SVG
In this sandbox I have a react app example with an iFrame that loads an HTML file and adds a click event listener to it.在这个沙箱中,我有一个带有 iFrame 的反应应用程序示例,它加载 HTML 文件并向其添加单击事件侦听器。
The reason is to detect href
s on click and act accordingly.原因是在点击时检测
href
并采取相应措施。 The HTML also includes an SVG part that I have a problem getting the href
with the hostname. 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>
getting the href
with the following snippet from MouseEvent
从
MouseEvent
获取带有以下代码段的href
let target = event.target! as HTMLAnchorElement;
const link = isHyperlink(target) ? target : closestATag(target);
if (!link) return;
const theHREF = link.href;
For the fist <a>
tag the href
is with correct and with hostname (ig http://localhost:3000/items/1234)对于第一个
<a>
标签, href
正确且带有主机名(ig http://localhost:3000/items/1234)
For the <a>
tag inside SVG the link.href returns SVGAnimatedString:{baseVal:string, animVal:string}
and getting href with link.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
does not contain hostname.对于 SVG 中的
<a>
标记,link.href 返回SVGAnimatedString:{baseVal:string, animVal:string}
并使用link.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
不包含主机名。
Thanks to @Frederic Brüning, my scenario was specific to handle all anchor links.感谢@Frederic Brüning,我的方案专门用于处理所有锚链接。
So the a tags in SVG does not need xlink:href="xxx"
but only href="xxx"
所以 SVG 中的 a 标签不需要
xlink:href="xxx"
而只需要href="xxx"
then the getAttributeNS
does not need namespace.那么
getAttributeNS
不需要命名空间。 getAttributeNS('','href')
which returns href
(exact string value) for any <a>
tag getAttributeNS('','href')
) 为任何<a>
标签返回href
(确切的字符串值)
Then appending origin will fix my problem然后附加原点将解决我的问题
theUrl = `${window.location.origin}${link.getAttributeNS('','href')}`
You can get the uri adding xlink: before the href attributes in your anchor tags.您可以在锚标签中的 href 属性之前添加 xlink: 的 uri。 Maybe then add the current location like this:
也许然后像这样添加当前位置:
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>
You can also get the baseURI from the node element of the attribute.您还可以从属性的节点元素中获取 baseURI。
let node = link.getAttributeNodeNS("http://www.w3.org/1999/xlink", "href")
node.baseURI + node.value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.