gpt4 book ai didi

javascript - 在 D3.js 中选择拖动元素下方的元素

转载 作者:太空宇宙 更新时间:2023-11-04 15:31:14 25 4
gpt4 key购买 nike

我想选择被拖动元素下方的元素,同时拖着。应使用鼠标光标完成选择,不需要对拖动对象进行边界检查,只需常规的鼠标悬停事件即可。

示例代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.active {
stroke: #000;
stroke-width: 2px;
}

</style>
<svg width="960" height="500"></svg>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = 32;

var circles = d3.range(2).map(function() {
return {
x: Math.round(Math.random() * (width - radius * 2) + radius),
y: Math.round(Math.random() * (height - radius * 2) + radius)
};
});

var color = d3.scaleOrdinal()
.range(d3.schemeCategory20);

svg.selectAll("circle")
.data(circles)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", radius)
.style("fill", function(d, i) { return color(i); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));

function dragstarted(d) {
d3.select(this).raise().classed("active", true);
}

function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function dragended(d) {
d3.select(this).classed("active", false);
}

</script>

怎么做呢?

.on("mouseenter", function() {d3.select(this)... })

不起作用,因为该对象位于拖动的对象下方,因此 onhover/onmouseenter/etc 事件不会激活,我需要它们激活

最佳答案

只需在拖动开始时将其“pointer-events”设置为“none”,您就可以让鼠标事件作用于被拖动对象下方的对象。

function dragstarted(d) {
d3.select(this).raise().classed("active", true);
d3.select(this).attr('pointer-events', 'none');
}

不要忘记在拖尾时将其删除,以便可以再次拖动该对象。

function dragended(d) {
d3.select(this).attr('pointer-events', null)
d3.select(this).classed("active", false);
}

这是@分散的稍微修改过的 fiddle 来展示它:https://jsfiddle.net/samuel365/10gLvxde/215/

关于javascript - 在 D3.js 中选择拖动元素下方的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44763121/

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