jQuery UI Draggable + CSS Transform Causes “Jumping”

后端 未结 6 1184
既然无缘
既然无缘 2021-02-08 06:09

EDIT: I solved it. But StackOverflow isn\'t letting me mark my answer as the solution, so I simply am not going to.

I\'m having an issue with regard to

6条回答
  •  失恋的感觉
    2021-02-08 06:24

    I found the solution.

    The solution is the completely avoid position:absolute; when using Draggable and CSS transforms. You can easily get manipulate anything from absolute/window/whatever coordinates into relative, so that's just what I did.

    In my case, I was spawning a Draggable element underneath the mouse. I calculated the relative position based on the mouse position with the offset() of the element (both in window coordinates) and then divided by the scale of the parent div.

    Here's a snippet:

    // ops.[x|y] is the mouse position in window coords
    // parentDiv.offset().[left|right] is the div position in window coords
    
    // get the scale transform matrix from our poorly written panzooming lib
    var mtx = graph.parentDiv.panzoom('getMatrix');
    var zx = mtx[0];
    var zy = mtx[3];
    
    // calculate the relative position
    var x = (ops.x - parentDiv.offset().left) / zx;
    var y = (ops.y - parentDiv.offset().top) / zy;
    
    // set some initial css
    parentDiv.css('position', 'relative')
             .css('left', x + 'px')
             .css('top', y + 'px');
    
    // initialize the draggable
    parentDiv.draggable({
        stack: $(graph.parentDiv).children(),
        drag: function(e, ui){
            var mtx = graph.parentDiv.panzoom('getMatrix');
            var zoomScaleX = mtx[0];
            var zoomScaleY = mtx[3];
    
            // scale the delta by the zoom factor
            var dx = ui.position.left - ui.originalPosition.left;
            var dy = ui.position.top - ui.originalPosition.top;
    
            ui.position.left = ui.originalPosition.left + (dx / zoomScaleX);
            ui.position.top = ui.originalPosition.top + (dy / zoomScaleY);
        }
    });
    

提交回复
热议问题