La parte del truco podría ser viewBox="-50 0 150 100"
. Pero realmente necesito obtener las coordenadas negativas.
Por favor, eche un vistazo a la demostración a continuación:
$('svg').click(function(e){ const { farthestViewportElement: svgRoot } = e.target; const dim = svgRoot.getBoundingClientRect(); const x = e.clientX - dim.left; const y = e.clientY - dim.top; $('#cord-track').val(`x: ${x}, y: ${y}`); })
svg {border:1px dashed blue}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>When you click mouse in the red rect, it works perfectly</p> <p>When you click mouse in the left blank zone, it throws an error, so that I can't trace my x and y values. How do I fix it?</p> <svg width="100px" id="test" viewBox="-50 0 150 100"> <rect x="0" y="0" width="100" height="100" fill="red"> </svg> <input id="cord-track" />
https://www.google.com/search?q=FartestViewportElement
La documentación para FarthestViewportElement
dice:
El elemento 'svg' del ancestro más lejano.
Nulo si el elemento actual es el elemento svg más externo
Por lo tanto, cuando hace clic en <svg>
, obtiene un valor null
Entonces, en su lugar, obtenga ese <svg>
con e.target.closest("svg")
Nota: esto, por supuesto, fallará cuando tenga <svg>
dentro <svg>
;
use un <rect>
de tamaño completo como primer elemento y luego para capturar todo
MYSVG.onclick = e => { let svg = e.target.closest("svg"); let path = e.composedPath().map(el => el.nodeName ).join(","); console.log("CLICKED:",e.target.nodeName,"IN:",svg.id,"CLICK PATH:",path); }
svg { width:180px; border: 1px dashed blue }
<svg id="MYSVG" viewBox="-50 0 150 100"> <rect x="0" y="0" width="100" height="100" fill="red"/> </svg>