gpt4 book ai didi

javascript - 检测鼠标按下时单击的元素

转载 作者:行者123 更新时间:2023-12-03 08:36:26 25 4
gpt4 key购买 nike

我正在尝试找到一种方法来获取启动鼠标按下行为时正在单击的元素,其工作原理与此类似:

function mousedrag(d){
if(selectedObject == rectangle)
{
...
}
else if(selectedObject == circle){
...
}
else{
...
}
}

请帮忙,提前致谢

最佳答案

在鼠标拖动中使用this.nodeName:

function mousedrag() {
if (this.nodeName === "circle"){
// it's a circle
} else if (this.nodeName === "rect"){
// it's a rectangle
}
}

完整的工作示例:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>

var width = 500,
height = 500,
radius = 20;

var drag = d3.behavior.drag()
// .origin(function(d) { return d; })
.on("drag", dragmove);

var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);

svg.append("circle")
.attr("r", 20)
.attr("cx", 100)
.attr("cy", 100)
.call(drag);

svg.append("rect")
.attr("width", 30)
.attr("height", 30)
.attr("x", 200)
.attr("y", 200)
.call(drag);

function dragmove() {
if (this.nodeName === "circle"){
d3.select(this)
.attr("cx", d3.event.x)
.attr("cy",d3.event.y);
} else if (this.nodeName === "rect"){
d3.select(this)
.attr("x", d3.event.x)
.attr("y",d3.event.y);
}
}
</script>
</body>

关于javascript - 检测鼠标按下时单击的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201714/

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