我正在嘗試使用 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 來插入 rect 元素和錨點。單獨插入元素是可行的,但是當我嘗試將其插入錨點時,什么也沒有出現。這是我的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>");
任何想法為什么我的代碼不起作用?
uj5u.com熱心網友回復:
要使用 svg 物件創建鏈接,您應該使用 svg 錨而不是 html 錨。所以更換
var aTag = document.createElement('a');
經過
var aTag = document.createElementNS("http://www.w3.org/2000/svg", "a")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454214.html
標籤:javascript html svg
