简体   繁体   中英

Inserting rect element inside anchor in svg with javascript doesn't work

I am trying to create a clickable image using svg. Inside the svg I would have multiple rect elements (the parts of the image that I want to be clickable) and around them I would put anchor elements to make them clickable. When I do this using only html, it works without an issue:

 <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>

However, I need to do this dynamically, so I want to use javascript in order to insert the rect element and the anchor. Inserting the element alone works, but when I try to insert it inside an anchor, nothing shows up. Here is my javascript code:

 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>");

Any ideas why my code doesn't work?

For creating a link with an svg object, you should use an svg anchor rather than an html anchor. So replace

var aTag = document.createElement('a');

by

var aTag = document.createElementNS("http://www.w3.org/2000/svg", "a")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM