简体   繁体   中英

How to add a click event inside a shape in a SVG?

In this demo below If you click on the stroke the alert is triggered, How can I make it in such a way that even if they click anywhere inside the rectangle and I alerts.

 const svg = document.querySelector('#svg'); const svgNS = svg.namespaceURI; const rect = document.createElementNS(svgNS, 'rect'); const clickedOnRect = () => { alert('Rectangle was clicked'); } rect.setAttributeNS(null, 'x', '100'); rect.setAttributeNS(null, 'y', '100'); rect.setAttributeNS(null, 'width', '100'); rect.setAttributeNS(null, 'height', '100'); rect.setAttributeNS(null, 'fill', "none"); rect.setAttributeNS(null, 'stroke', "red"); rect.setAttributeNS(null, 'stroke-width', '5'); rect.setAttributeNS(null, 'tab-index', '1'); rect.setAttributeNS(null, 'cursor', 'pointer'); rect.addEventListener('click', ($event) => { clickedOnRect(); }); svg.appendChild(rect); 
 svg { border: 1px solid #000000; } 
 <svg id='svg' width="400" height="400"> </svg> 

Replace none filling with the transparent one.

 const svg = document.querySelector('#svg'); const svgNS = svg.namespaceURI; const rect = document.createElementNS(svgNS, 'rect'); const clickedOnRect = () => { alert('Rectangle was clicked'); } rect.setAttributeNS(null, 'x', '100'); rect.setAttributeNS(null, 'y', '100'); rect.setAttributeNS(null, 'width', '100'); rect.setAttributeNS(null, 'height', '100'); rect.setAttributeNS(null, 'fill', "transparent"); rect.setAttributeNS(null, 'stroke', "red"); rect.setAttributeNS(null, 'stroke-width', '5'); rect.setAttributeNS(null, 'tab-index', '1'); rect.setAttributeNS(null, 'cursor', 'pointer'); rect.addEventListener('click', ($event) => { clickedOnRect(); }); svg.appendChild(rect); 
 svg { border: 1px solid #000000; } 
 <svg id='svg' width="400" height="400"> </svg> 

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