我正在尝试制作各种SVG编辑器。长话短说,我需要将鼠标事件附加到给定SVG中特定深度的<g>
元素上。由于各种原因,我无法提前知道ID。 SVG非常庞大,将包含数百甚至数千个元素。
d3.selectAll("svg > g > g > g").select("g").on("mouseover", function() {
console.log("mouseover");
}).on("mouseout", function() {
console.log("mouseout");
}).on("click", function() {
console.log("clicked");
});
该代码有效,但是开始之前需要很长时间。假设我有十个这样的元素将与该特定选择匹配。似乎在页面加载后的每一秒中,实际上十个鼠标中的另一个实际上都附加了鼠标事件。我想知道是否可以在d3每次附加事件时打印控制台事件,或者我如何知道d3是否附加了它需要附加的所有内容。
基本上,此JSFiddle需要更快地加载鼠标事件。如果您等待几秒钟,您将看到越来越多的盒子在工作。
最佳答案
这是一个非常有趣的问题,我设法使它起作用,但是我没有解释为什么它起作用。如果有深入知识的人可以解释这一点,将不胜感激。
慢的:
var targetElements = d3.selectAll("svg > g > g").select("g").select("g").select("path");
targetElements.on("mouseover", function() {
d3.select(this)
.style("fill", "orange");
}).on("mouseout", function() {
d3.select(this)
.style("fill", "BLUE");
}).on("click", function() {
d3.select(this)
.style("fill", "green");
});
快速地:
var targetElements = d3.selectAll("svg > g > g").select("g").select("g").select("path");
targetElements.style('fill', 'white'); // Black magic - comment this out and the event handler attachment is delayed alot
targetElements.on("mouseover", function() {
d3.select(this)
.style("fill", "orange");
}).on("mouseout", function() {
d3.select(this)
.style("fill", "BLUE");
}).on("click", function() {
d3.select(this)
.style("fill", "green");
});
区别仅在于在将事件处理程序附加到元素之前将填充应用于元素-
.style("fill", "white").on("mouseover",
fiddle 演奏-https://jsfiddle.net/v8e4hnff/1/
注意:还尝试用SVG元素上的JS native 选择器和事件处理程序附件实现,这比D3快得多。行为在IE11和Chrome上相同。
如上所述,如果有人可以解释该行为,请这样做!
关于javascript - 如何/何时将事件监听器附加到d3.js中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41768276/