简体   繁体   English

D3.js如何防止点击事件上的拖曳启动

[英]D3.js how prevent drag-start on click event

I am using D3.js v4 library. 我正在使用D3.js v4库。 I need to discriminate between click and drag-start event: if it is a click event, I don't want the drag-start to be fired. 我需要区分单击事件和拖动开始事件:如果这是单击事件,则我不希望触发拖动开始。 It seems it is possible the other way around (prevent click if dragstart is fired). 似乎有可能采取其他方法(如果启动dragstart则防止单击)。 Any idea if this is doable? 知道这是否可行吗?

 var svg = d3.select("#svgContainer").append("svg") .attr("width", 100) .attr("height", 100); var onDrag = d3.drag() .on("start", function() { $("#console").append('<p>drag-start</p>'); console.log("drag-start"); }) .on("drag", function() { }) .on("end", function() { }); var box = svg.append("rect") .attr("x", 25) .attr("y", 25) .attr("width", 50) .attr("height", 50) .attr("fill", "orange") .on("click", function() { $("#console").append('<p>click</p>'); console.log("click"); }) .call(onDrag); $("#btn").click(function() { $("#console").empty(); }); 
 p { line-height: 8px; font-size: 8px; } #svgContainer { display:block; width: 100px; height: 100px; background-color: #333; } #console { display: block; width: 100%; height: 400px; overflow: scroll; } #btn { position: absolute; top: 70px; left: 150px; width: 50px; height: 30px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.2/d3.js"></script> <div id="svgContainer"></div> <div id="console"></div> <button id="btn">Clear</button> 

Just spitballing here, but I would probably do something like: 只是在这里吐口水,但我可能会做类似的事情:

var dragger = null;
var onDrag = d3.drag()
    .on("start", function() {
        dragger = setTimeout(function() {
            $("#console").append('<p>drag-start</p>');  
            console.log("drag-start");
        }, 100);
    });
var box = svg.append("rect")
    .attr("x", 25)
    .attr("y", 25)
    .attr("width", 50)
    .attr("height", 50)
    .attr("fill", "orange")
    .on("click", function() {
         $("#console").append('<p>click</p>');
         console.log("click");
         clearTimeout(dragger);
     })
    .call(onDrag);

So, your drag start will be delayed by 100ms (or whatever you want), and if the click happens before that delay, it cancels the timeout. 因此,您的拖动开始将延迟100毫秒(或您想要的任何延迟),如果单击发生在该延迟之前,它将取消超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM