【问题标题】:How to add a click event inside a shape in a SVG?如何在 SVG 的形状内添加点击事件?
【发布时间】:2019-12-30 02:06:04
【问题描述】:

在下面的这个演示中,如果单击触发警报的笔划,我怎样才能做到这一点,即使他们单击矩形内的任意位置并发出警报。

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>

【问题讨论】:

    标签: svg onclick svg-rect


    【解决方案1】:

    transparent 替换none 填充。

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 2015-04-06
      • 1970-01-01
      相关资源
      最近更新 更多