使用 javascript 在 svg 中的锚点内插入矩形元素不起作用
Inserting rect element inside anchor in svg with javascript doesn't work
我正在尝试使用 svg 创建可点击的图像。在 svg 内部我会有多个 rect 元素(图像中我想要可点击的部分)并且在它们周围我会放置锚元素以使它们可点击。
当我仅使用 html 执行此操作时,它可以正常工作:
<a href="test.html">
<rect
style="fill:#00ff00;stroke-width:0.264583"
id="rect142"
width="33.816833"
height="24.259901"
x="172.39232"
y="63.95792" />
</a>
但是,我需要动态执行此操作,所以我想使用 javascript 来插入矩形元素和锚点。单独插入元素是可行的,但是当我尝试将其插入锚点时,什么也没有显示。这是我的 javascript 代码:
console.log("in")
// make a simple rectangle
var newRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
newRect.setAttribute("id", "rect604-1");
newRect.setAttribute("x", "172.39232");
newRect.setAttribute("y", "63.95792");
newRect.setAttribute("width", "33.816833");
newRect.setAttribute("height", "24.259901");
newRect.setAttribute("fill", "#00ff00");
newRect.setAttribute("opacity", "0.66");
newRect.setAttribute("fill-opacity", "1");
newRect.setAttribute("fill-rule", "evenodd");
newRect.setAttribute("stroke-width", "0.264583");
var aTag = document.createElement('a');
aTag.setAttribute('href',"test.html");
var svg = document.getElementById("svg12");
console.log(svg)
// append the new rectangle to the svg
aTag.appendChild(newRect);
svg.appendChild(aTag);
//$("#rect604-1").wrap("<a href='https://mail.google.com/mail/u/0/#inbox'></a>");
知道为什么我的代码不起作用吗?
要使用 svg 对象创建 link,您应该使用 svg 锚点而不是 html 锚点。所以替换
var aTag = document.createElement('a');
来自
var aTag = document.createElementNS("http://www.w3.org/2000/svg", "a")
我正在尝试使用 svg 创建可点击的图像。在 svg 内部我会有多个 rect 元素(图像中我想要可点击的部分)并且在它们周围我会放置锚元素以使它们可点击。 当我仅使用 html 执行此操作时,它可以正常工作:
<a href="test.html">
<rect
style="fill:#00ff00;stroke-width:0.264583"
id="rect142"
width="33.816833"
height="24.259901"
x="172.39232"
y="63.95792" />
</a>
但是,我需要动态执行此操作,所以我想使用 javascript 来插入矩形元素和锚点。单独插入元素是可行的,但是当我尝试将其插入锚点时,什么也没有显示。这是我的 javascript 代码:
console.log("in")
// make a simple rectangle
var newRect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
newRect.setAttribute("id", "rect604-1");
newRect.setAttribute("x", "172.39232");
newRect.setAttribute("y", "63.95792");
newRect.setAttribute("width", "33.816833");
newRect.setAttribute("height", "24.259901");
newRect.setAttribute("fill", "#00ff00");
newRect.setAttribute("opacity", "0.66");
newRect.setAttribute("fill-opacity", "1");
newRect.setAttribute("fill-rule", "evenodd");
newRect.setAttribute("stroke-width", "0.264583");
var aTag = document.createElement('a');
aTag.setAttribute('href',"test.html");
var svg = document.getElementById("svg12");
console.log(svg)
// append the new rectangle to the svg
aTag.appendChild(newRect);
svg.appendChild(aTag);
//$("#rect604-1").wrap("<a href='https://mail.google.com/mail/u/0/#inbox'></a>");
知道为什么我的代码不起作用吗?
要使用 svg 对象创建 link,您应该使用 svg 锚点而不是 html 锚点。所以替换
var aTag = document.createElement('a');
来自
var aTag = document.createElementNS("http://www.w3.org/2000/svg", "a")