Fixing jQuery Drag/Resize with CSS Transform Scale
Background
Applying CSS transforms to an element and then using jQuery's draggable and resizable plugins on its children can introduce misalignment between the mouse cursor and the dragged or resized element. This is due to the scale factor applied to the element.
jQuery Patching Solution
A previous solution involved patching jQuery's draggable and resizable plugins to adjust the mouse offset by the scale factor. This method required modifying the source code of the plugins.
Alternative Solution: Callback Handlers
An alternative solution is to use callback handlers provided by the resizable and draggable plugins. This eliminates the need for patching jQuery.
Resizable Fix
<br>$(this).resizable({</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">minWidth: -(contentElem.width()) * 10, minHeight: -(contentElem.height()) * 10, resize: function(event, ui) { var changeWidth = ui.size.width - ui.originalSize.width; var newWidth = ui.originalSize.width + changeWidth / zoomScale; var changeHeight = ui.size.height - ui.originalSize.height; var newHeight = ui.originalSize.height + changeHeight / zoomScale; ui.size.width = newWidth; ui.size.height = newHeight; }
});
In the resize handler, calculate the change in width and height, apply the inverse of the zoom scale to adjust the new width and height, and update the ui.size object accordingly.
Draggable Fix
<br>$(this).draggable({</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">handle: '.drag-handle', start: function(event, ui) { ui.position.left = 0; ui.position.top = 0; }, drag: function(event, ui) { var changeLeft = ui.position.left - ui.originalPosition.left; var newLeft = ui.originalPosition.left + changeLeft / (( zoomScale)); var changeTop = ui.position.top - ui.originalPosition.top; var newTop = ui.originalPosition.top + changeTop / zoomScale; ui.position.left = newLeft; ui.position.top = newTop; }
});
In the drag handler, calculate the change in left and top positions, apply the inverse of the zoom scale to adjust the new left and top positions, and update the ui.position object accordingly.
Conclusion
This alternative solution using callback handlers provides a non-invasive way to correct the drag/resize behavior when CSS transforms with scale are applied.
The above is the detailed content of How to Achieve Correct jQuery Drag/Resize Behavior with CSS Transform Scale?. For more information, please follow other related articles on the PHP Chinese website!