PDA

View Full Version : [Javascript] Aggiungere elemento <a>


das
30-08-2015, 14:20
Ho la necessità di trasformare alcuni hotspot di immagini SVG in elementi cliccabili.
Non posso sfruttare l'evento onclick perchè le immagini saranno mostrate su android e in webview l'evento onclick non c'è a meno di rinunciare al pan e allo zoom con le dita.

Devo per forza quindi introdurre nelle svg degli elementi <a> al caricamento. In questo modo posso poi cliccarci sopra con ilo dito. Gli hotspot sono rappresentati da dei cerchi e hanno un id.
Ho quindi realizzato questa funzione che disegna un cerchio più grande intorno a quello iniziale e lo mette all'interno di un tag <a> in modo che sia cliccabile.

Il cerchio compare perfettamente ma la zona non è cliccabile. La cosa stranissima è che se tramite console.log prendo le modifiche fatte dal javascript e le copio manualmente nel file allora tutto funziona.


<html>
<head>
</head>
<body>

<object width=100% height=100% id="svgObject" type="image/svg+xml" data="prova.svg"></object>

<script>
function hotspoHyperlink(elemento){
var a = document.getElementById("svgObject");
var svgDoc = a.contentDocument;
var svgItem = svgDoc.getElementById(elemento);
if (svgItem=="[object SVGCircleElement]"){
var r = svgItem.getAttributeNode("r");
var stroke_width = svgItem.getAttributeNode("stroke-width");
var transform = svgItem.getAttributeNode("transform");

var newR = document.createAttribute("r");
newR.value=2*r.value;
var newStroke_width = document.createAttribute("stroke-width");
newStroke_width.value=stroke_width.value;
var newTransform = document.createAttribute("transform");
newTransform.value=transform.value;
var stroke = document.createAttribute("stroke");
stroke.value="#00FF00";
var newItem = document.createElementNS("http://www.w3.org/2000/svg","circle");
var opacity = document.createAttribute("opacity");
opacity.value= 0.5;
newItem.setAttributeNode(newR);
newItem.setAttributeNode(newStroke_width);
newItem.setAttributeNode(newTransform);
newItem.setAttributeNode(stroke);
newItem.setAttributeNode(opacity);

var linkTag = document.createAttribute("xlink:href");
linkTag.value="https://www.google.it";
var targetLink = document.createAttribute("target");
targetLink.value="_top";
var link = document.createElementNS("http://www.w3.org/2000/svg","a");
link.setAttributeNode(linkTag);
link.setAttributeNode(targetLink);
link.appendChild(newItem);

svgItem.parentNode.insertBefore(link, svgItem.nextSibling);
}
}
</script>
<button onclick="hotspoHyperlink('hotspot1')">Click</button>
</body>
</html>


Cosa può essere ? Succede lo stesso con firefox e IE.