gpt4 book ai didi

javascript - 将元素移到前面而不中断事件

转载 作者:行者123 更新时间:2023-11-29 21:15:48 25 4
gpt4 key购买 nike

我正在尝试修复我正在处理的一些事件代码。在这种特殊情况下,我需要能够订阅 svg:circle 上的 click 事件。但是,还需要在 mousedown 上将圆圈移动到 z-index 的顶部,以便可以将元素拖动到其他元素的顶部。

这样做的方法是将元素从 DOM 中取出,然后使用我在 http://bl.ocks.org/eesur/4e0a69d57d3bfc8a82c2 中使用的辅助函数将其重新插入到正确的位置。 .这样做的问题是事件链似乎已经中断,将元素从 dom 中移除,从而阻止了 click 事件的触发。

我想知道是否有人可以想出更好的方法来确保 click 正确触发,但仍允许在拖动生命周期中某处更改 z-index?

这个小例子展示了 z-index 是如何变化的,但是点击事件并没有在控制台中触发。一旦元素位于顶部,再次点击该元素就会正确触发点击。

d3.selectAll("circle")
.on("mousedown", function() {
d3.select(this).moveToFront();
})
.on("click", function() {
var fill = d3.select(this).style("fill");
console.log("You clicked on : " + fill);
});

d3.selection.prototype.moveToFront = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
.red {
fill: red;
}
.blue {
fill: blue;
}
.green {
fill: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<svg width="600" height="600">
<circle class="red" cx="50" cy="50" r="50" />
<circle class="blue" cx="100" cy="100" r="50" />
<circle class="green" cx="150" cy="150" r="50" />
</svg>

最佳答案

我想出了一个有点古怪的想法,这个想法似乎可行,但如果 DOM 中有很多元素,我对性能有点担心。

这个想法本质上是,不是将选择(在 mousedown 上)移动到顶部,而是移动其他所有内容(相同类型,在本例中为 svg:circle) 在被鼠标按下的元素后面。

d3.selectAll("circle")
.on("mousedown", function() {
var that = this;
d3.select(this.parentNode)
.selectAll("circle")
.filter(function() { return this !== that; })
.moveBehind(that);
})
.on("click", function() {
var fill = d3.select(this).style("fill");
console.log("You clicked on : " + fill);
});

d3.selection.prototype.moveToFront = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};

d3.selection.prototype.moveBehind = function(element) {
return this.each(function() {
this.parentNode.insertBefore(this, element);
});
};
.red {
fill: red;
}
.blue {
fill: blue;
}
.green {
fill: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js"></script>
<svg width="600" height="600">
<circle class="red" cx="50" cy="50" r="50" />
<circle class="blue" cx="100" cy="100" r="50" />
<circle class="green" cx="150" cy="150" r="50" />
</svg>

关于javascript - 将元素移到前面而不中断事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39446325/

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