gpt4 book ai didi

javascript - d3 : UI lags when mouse events attached to 1000 nodes

转载 作者:行者123 更新时间:2023-11-30 21:00:05 25 4
gpt4 key购买 nike

我有一个用例,我有大约 1000 个 DOM 元素,并且所有元素都附加到 mouseover 和 mouseout 事件。

代码是这样的

    onMouseover(node, targetNode) {
window.cancelAnimationFrame(this.mouseoutAnimationFrame);
window.cancelAnimationFrame(this.mouseoverAnimationFrame);
this.mouseoverAnimationFrame = window.requestAnimationFrame(function() {
svg.selectAll('use').classed('fadeOut', true);
svg.selectAll('line').classed('fadeOut', true);
svg.selectAll('text').classed('fadeOut', true);
d3.select(targetNode).classed('fadeOut', false);
d3.select(targetNode.nextElementSibling).classed('fadeOut', false);
...some more code
return this;
}


onMouseout(node, target) {
var svg = d3.select(target.ownerSVGElement);

this.mouseoutAnimationFrame = window.requestAnimationFrame(function() {
svg
.selectAll('use')
.classed('fadeOut', false)
.classed('fadeIn', true);
svg
.selectAll('text')
.classed('fadeOut', false)
.classed('fadeIn', true);
});
return this;
}

registerListernerWithDelay(ele, delay, mouseoverCb, mouseoutCb) {
var timeout = null;
var event;

ele.on('mouseover', function(d) {
event = d3.event;
timeout = setTimeout(function() {
mouseoverCb(d, event);
}, delay);
});

ele.on('mouseout', function(d) {
clearTimeout(timeout);
event = d3.event;
mouseoutCb(d, event);
});
}
// I tried adding 400ms delay..still facing same issue
this.registerListernerWithDelay(nodes, 400,
function mouseover(d, event) {
var target = event.target;
self.onMouseover(d, target);
},
function mouseout(d,event) {
var target = event.target;
self.onMouseout(d, target);
}
);

所以每当我悬停到元素时..我会看到显示信息的踪迹,理想情况下应该在鼠标移出时将其删除。请建议我如何克服这个错误。我也尝试添加延迟,仍然没有成功。

最佳答案

您可以使用 event delegation解决这个问题。

您不必为每个 DOM 节点设置一个监听器,而只需在父节点上使用一个监听器。然后,无论事件何时发生,您都可以查找 event.target 以确定应该为哪个节点设置动画。

示例实现,假设您有以下 html:

<svg id="parentNode">
<!-- All the interactive nodes are here... -->
</svg>

然后这个 javascript 就可以了:

d3.selectAll('#parentNode') // this is only one item
.on('mouseover', function() {
var element = d3.select(d3.event.target)
// element is the DOM node with which you want to interact...
})
.on('mouseout', function() {
var element = d3.select(d3.event.target)
// [...]
})

关于javascript - d3 : UI lags when mouse events attached to 1000 nodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com