d3.event.y has strange values during drag behavior

寵の児 提交于 2019-12-12 14:32:13

问题


I'm creating an example illustrating a layout with resizeable cells using the D3 drag behaviour and CSS {display: table} styles. It works fine for dragging horizontally, but not vertically. For vertical resizing, d3.event.y is providing values that do not make sense to me.

Here is a fiddle showing the working horizontal drag and the broken vertical drag. Take a look at the console output while dragging to see that the values returned by d3.event match the values returned by d3.mouse() for the horizontal drag, but they diverge for the vertical drag.

I can fix the behaviour by using the d3.mouse() y-coordinate instead of the d3.event y-coordinate. To see this, comment out the "DOESN'T WORK" line and uncomment the "WORKS" line. However, I don't understand why I need to do this, and it seems less general in that I have to assume a mouse input instead of using the more generic d3.event.

Is this a bug, or am I failing to understand something here?

Note that this question seems to be hitting the same issue, but using HTML tables instead of CSS tables. I thought it would be helpful to document that this problem is occurring in both contexts.

Also note that commenting out the two lines that actually do the vertical resizing, commented with "RESIZE CELLS", makes the d3.event work correctly. Of course, the table doesn't get resized then. This suggests that it is something about the act of resizing the divs that is leading d3.event astray.


回答1:


Alright, I think I've figured out the issue. If you look at the code for drag behavior, you'll notice in dragstart that the value used to calculate the mouse offset is based off this.parentNode. In short, it uses this.parentNode as a reference point, and assumes that it's going to be stable for the duration of the drag. You're modifying the parent nodes during the drag, so its reference point gets, to put it technically, pretty borked. In this case, using d3.mouse is your best bet, since d3.event.y is only going to be reliable as long as the parent node stays in place.

The reason this only happens in the y direction for you is that the x position of all the rows, which are the parent nodes here, stay constant, whereas the y component changes during the drag.

The relevant code sections:

parent = that.parentNode,
function moved() {
    var position1 = position(parent, dragId), dx, dy;

    //...

    dispatch({
      type: "drag",
      x: position1[0] + dragOffset[0],
      y: position1[1] + dragOffset[1],
      dx: dx,
      dy: dy
    });


来源:https://stackoverflow.com/questions/25075402/d3-event-y-has-strange-values-during-drag-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!