Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
Estilos SVG en línea Responde cuando no se usan grupos, pero deja de responder con grupos

Estoy usando Javascript para crear dinámicamente un elemento SVG compuesto por varias formas. Los objetos se crean dinámicamente, como se hace en este violín.

La llamada a la función onclick debería cambiar el relleno de amarillo a negro y viceversa, y aunque parece sencillo, por supuesto que no lo es :)

 function toggleFill() { let w = document.getElementById("svgCircle1"); //let isYellow = w.getAttribute('fill') == 'yellow'; let isYellow = w.style.fill == 'yellow'; console.log("w> " + w); console.log("fill> " + w.style.fill); if (isYellow) { //w.setAttribute('fill', 'black'); w.style.fill = "black"; } else { //w.setAttribute('fill', 'yellow'); w.style.fill = "yellow"; } } function doDrawing(x, y, r) { const svgNS = "http://www.w3.org/2000/svg"; let svg = document.querySelector("svg"); function drawCircle(cx, cy, r) { let c = document.createElementNS(svgNS, "circle"); c.setAttribute("id", "svgCircle1"); c.setAttribute("class", "svgCircle"); c.setAttribute("cx", cx); c.setAttribute("cy", cy); c.setAttribute("r", r); c.setAttribute("onclick", "toggleFill();"); return c; } g = document.createElementNS(svgNS, "g"); g.setAttribute("id", "svgG1"); g.appendChild(drawCircle(x, y, r)); svg.appendChild(g); }
 .svgCircle { fill: yellow; }
 <button id="button1" onclick="doDrawing( 50, 50, 10 );">Draw</button> <svg width="1000" height="400" id="drawing"> </svg>

El problema es que a veces el atributo de estilo estará vacío, a veces tendrá el valor correcto y no se actualizará, y algunas veces funcionará.

Si elimino el grupo, se ejecuta correctamente. Veo el mismo comportamiento con el acceso al atributo style.fill que con la llamada al método getAttribute.

Pensé que tal vez el estilo de clase se estaba volviendo a aplicar al objeto por alguna razón desconocida, pero agregar classList.remove tampoco resolvió el problema.

Puedo solucionar este problema invirtiendo la lógica if y usando mi conocimiento del color inicial, luego configurando la variable en negro si no coincide. Una vez que se ejecuta el JS setAttribute o style.fill inicial, el código se vuelve confiable.

Estoy seguro de que hay algo básico que he pasado por alto, prefiero entender lo que me perdí que confiar en el trabajo.

En caso de que sea relevante, lo he estado probando en Chrome.

¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe ceñirse a una forma de agregar el relleno, ya sea como un atributo o en CSS.

También eliminé la identificación. Ahora no sé el caso de uso, pero las identificaciones deben ser únicas y usted apunta a una identificación específica en su función. Entonces, aquí solo tengo un detector de eventos para todo el SVG.

 document.querySelector("svg").addEventListener('click', e => { let w = e.target; if (w.nodeName == 'circle') { let isYellow = w.style.fill == 'yellow'; console.log("w> " + w); console.log("fill> " + w.style.fill); if (isYellow) { //w.setAttribute('fill', 'black'); w.style.fill = "black"; } else { //w.setAttribute('fill', 'yellow'); w.style.fill = "yellow"; } } }); function doDrawing(x, y, r) { const svgNS = "http://www.w3.org/2000/svg"; let svg = document.querySelector("svg"); function drawCircle(cx, cy, r) { let c = document.createElementNS(svgNS, "circle"); c.setAttribute("class", "svgCircle"); c.setAttribute("cx", cx); c.setAttribute("cy", cy); c.setAttribute("r", r); c.style.fill = "yellow"; return c; } g = document.createElementNS(svgNS, "g"); g.setAttribute("id", "svgG1"); g.appendChild(drawCircle(x, y, r)); svg.appendChild(g); }
 <button id="button1" onclick="doDrawing( 50, 50, 10 );">Draw</button> <svg width="1000" height="400" id="drawing"> </svg>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!