簡體   English   中英

在d3中使用其他元素執行雙鼠標事件

[英]Performing double mouseup events with other element in d3

我試圖在我的節點上發出一個鼠標事件,用於在mousedown上出現的周圍弧。

我的預期功能是能夠按住節點並將其拖動到弧形中,觸發弧線以及節點的mouseup事件。 在使用下面的JSFiddle中引用的當前代碼時遇到問題,非常感謝您的幫助!

對於我的弧線,我有以下代碼,我希望在將鼠標放在特定弧線上方時執行鼠標操作:

slices.append('path')
    ...
    .on('mouseup', function(arc) {
        console.log(arc.data.title)
    }
);

我還希望在特定弧頂部拖動節點並釋放鼠標按鈕后運行節點的鼠標:

svg.append("g")
        .attr("class", "node")
        .selectAll(".bubble")
          .data(data, function(d){ return d.id; })
        .enter().append("circle")
        ...
        .on('mousedown', nodeClickedArcs)
        .on('mouseup', removeArcs)

謝謝!

http://jsfiddle.net/uas6zr7y/3/

這里的關鍵挑戰是鼠標事件基本上被圓圈吸收。 您也許可以這樣的方式對元素進行排序,即弧的父g保持帶有圓圈的子g ,以允許事件傳播到相關的父級,但是然后您的圓圈位於弧的下方。

我將在下面演示的一個選項是在拖動期間從節點剝離指針交互。 例如,這不會中斷拖動(在Chrome,Firefox,IE上測試),但允許鼠標與鼠標懸停/鼠標移出事件的其他元素進行交互。 然后我們可以監聽鼠標進入(並退出)目標形狀,如果拖動結束(鼠標向上)目標形狀,我們可以觸發特定動作。

這要求鼠標向上的所有事件邏輯都位於拖動結束功能中,但需要用於鼠標進入/退出目標形狀的監聽器。

基於以上所述,在下面的代碼片段中我:

  1. 在拖動時從拖動的節點(圓圈)中剝離指針事件。
  2. 監聽鼠標是否移動到目標形狀(矩形)上並更新該元素的基准以反映其“活動”狀態。 相反,如果鼠標移出目標形狀,我將節點設置為不活動。
  3. 如果拖動事件在目標形狀處於活動狀態時結束,那么我知道我的拖動節點已超過目標形狀(並且已經發生了鼠標向上)並且可以相應地執行操作。 如果拖動事件以沒有活動節點結束,則我將指針事件恢復到節點。

在下面的代碼段中,我刪除了節點(圓圈),如果它們在目標形狀(矩形)上,則更新過程中的矩形顏色:

 var svg = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 300); var drag = d3.drag() .on("drag",dragged) .on("end", dragEnd); var squares = svg.selectAll("rect") .data([{x:30},{x:130},{x:230},{x:330},{x:430}]) .enter() .append("rect") .attr("x", function(d) { return dx; }) .attr("y", 120) .attr("width", 40) .attr("height",40) .attr("fill","white") .on("mouseenter", function(d) { d.active = true; }) .on("mouseout", function(d) { d.active = false; }); var circles = svg.selectAll("circle") .data(d3.range(20)) .enter() .append("circle") .attr("cx", function(d) { return d/21*500 + 25; }) .attr("cy", function(d) { return d%2 * 40 + 50; }) .attr("r", 10) .attr("fill", function(d) { return d3.schemeCategory20[d]; }) .call(drag); function dragged(d) { var x = d3.mouse(this)[0]; var y = d3.mouse(this)[1]; d3.select(this) .attr("cx",x) .attr("cy",y) .style("pointer-events","none"); } function dragEnd(d) { var rect = squares.filter(function(d) { return d.active; }) if(!rect.empty()) { var circle = d3.select(this); rect.attr("fill",interpolateColor(rect,circle)); circle.remove(); } else { d3.select(this).style("pointer-events","all"); } } function interpolateColor(r,c) { return d3.interpolateLab(r.attr("fill"),c.attr("fill"))(0.5) } 
 svg { stroke: black; stroke-width: 2px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script> 

這會檢查鼠標位置,而不是圓圈與矩形重疊,碰撞檢測需要采用不同的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM