如何在SVG中的形状内添加点击事件?

时间:2019-08-25 18:00:11

标签: svg onclick svg-rect

在下面的演示中,如果您单击笔触,便会触发警报,我该如何做到这一点,即使他们单击矩形内的任何位置都会发出警报。

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>

1 个答案:

答案 0 :(得分:1)

none填充transparent

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>