Javascript 如何将事件侦听器添加到 svg 中的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12451855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:58:48  来源:igfitidea点击:

How to add event listeners to objects in a svg?

javascriptjqueryhtmlsvg

提问by mgalardini

I would like to create a web page displaying an interactive svg: since several svg may be used, the various objects displayed will have different IDs, so the event listeners (to catch a mouse click, for example) have to be dynamic.

我想创建一个显示交互式 svg 的网页:由于可能会使用多个 svg,因此显示的各种对象将具有不同的 ID,因此事件侦听器(例如捕捉鼠标单击)必须是动态的。

Starting from this snippet

这个片段开始

var a = document.getElementById("alphasvg");
a.addEventListener("load",function(){
        var svgDoc = a.contentDocument;
        var delta = svgDoc.getElementById("delta");
        delta.addEventListener("click",function(){alert('hello world!')},false);
    },false);

I would like to find a way to cycle through all the objects of the svg (maybe having a particular class) and attach an even listener to them.

我想找到一种方法来循环遍历 svg 的所有对象(可能有一个特定的类)并为它们附加一个偶数侦听器。

update

更新

So JQuery 'each' function may be a suitable option, but it seems that JQuery doesn't handle the svg DOM so well. Is there any other available option? (like a JQuery plugin?)

所以 JQuery 'each' 函数可能是一个合适的选项,但似乎 JQuery 并没有很好地处理 svg DOM。还有其他可用的选择吗?(像 JQuery 插件?)

采纳答案by methodofaction

This is my preferred structure for adding event listeners to SVG elements with vanilla js...

这是我使用 vanilla js 向 SVG 元素添加事件侦听器的首选结构...

// select elements
var elements = Array.from(document.querySelectorAll('svg .selector'));

// add event listeners
elements.forEach(function(el) {
   el.addEventListener("touchstart", start);
   el.addEventListener("mousedown",  start);
   el.addEventListener("touchmove",  move);
   el.addEventListener("mousemove",  move);
})

// event listener functions

function start(e){
  console.log(e);
  // just an example
}

function move(e){
  console.log(e);
  // just an example
}

The sample code you present is somewhat contrived, but here's a rewrite that makes it work...

您提供的示例代码有些人为,但这里有一个重写,使其工作......

var a = document.getElementById("alphasvg");
a.addEventListener("load",function(){
  var svgDoc = a.contentDocument;
  var els = svgDoc.querySelectorAll(".myclass");
  for (var i = 0, length = els.length; i < length; i++) {
    els[i].addEventListener("click", 
       function(){ console.log("clicked"); 
    }, false);
  }
},false);