如何将事件侦听器添加到 svg 中的对象? [英] How to add event listeners to objects in a svg?
问题描述
我想创建一个显示交互式 svg 的网页:由于可能会使用多个 svg,因此显示的各种对象将具有不同的 ID,因此事件侦听器(例如捕捉鼠标单击)必须是动态的.
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.
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);
我想找到一种方法来循环遍历 svg 的所有对象(可能有一个特定的类)并为它们附加一个偶数侦听器.
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.
更新
所以 JQuery 'each' 函数可能是一个合适的选项,但似乎 JQuery 并没有很好地处理 svg DOM.还有其他可用的选择吗?(像 JQuery 插件?)
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?)
推荐答案
这是我使用 vanilla js 向 SVG 元素添加事件侦听器的首选结构...
This is my preferred structure for adding event listeners to SVG elements with vanilla js...
// 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);
这篇关于如何将事件侦听器添加到 svg 中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!