首页  >  文章  >  web前端  >  如何使用 jQuery 的 Draggable() 和 resizing() 插件以及子元素上的 CSS 变换比例?

如何使用 jQuery 的 Draggable() 和 resizing() 插件以及子元素上的 CSS 变换比例?

Barbara Streisand
Barbara Streisand原创
2024-10-27 10:51:30365浏览

How to use jQuery's draggable() and resizable() plugins with CSS transform scale on child elements?

使用 CSS Transform Scale 进行 jQuery 拖动/调整大小

当对元素应用带有缩放功能的 CSS 变换,然后使用 jQuery 的可拖动时,会出现此问题() 和 resizing() 插件在该元素内的子元素上。问题是,由于应用的比例,基于 jQuery 的更改看起来与鼠标移动“不同步”。

原始解决方案

找到了修补的解决方案StackOverflow 上建议修改 jQuery 插件。具体来说,对 _mouseStart() 和 _generatePosition() 函数进行了更改以考虑缩放:

  • Monkey-patched _mouseStart() 以等于所应用的缩放比例的因子调整偏移值。
  • 在 _generatePosition() 中,根据比例因子调整移动,以确保拖动/调整大小的元素正确对齐。

改进的解决方案

随后,发现了更优雅的解决方案,无需修改 jQuery。此方法涉及为可调整大小和可拖动事件设置回调处理程序:

可调整大小:

$(this).resizable({
    // Set very large and negative minWidth and minHeight
    minWidth: -(contentElem.width()) * 10,
    minHeight: -(contentElem.height()) * 10, 
    resize: function(event, ui) {
        // Calculate the change in width and height
        var changeWidth = ui.size.width - ui.originalSize.width;
        var changeHeight = ui.size.height - ui.originalSize.height;

        // Adjust the new width and height by dividing the change by the zoomScale
        var newWidth = ui.originalSize.width + changeWidth / zoomScale;
        var newHeight = ui.originalSize.height + changeHeight / zoomScale;

        // Update the ui.size object with the adjusted values
        ui.size.width = newWidth;
        ui.size.height = newHeight;
    }
});

可拖动:

$(this).draggable({
    handle: '.drag-handle', // Specify a handle element for dragging
    start: function(event, ui) {
        // Reset the ui.position object to {left: 0, top: 0} at the start of the drag
        ui.position.left = 0;
        ui.position.top = 0;
    },
    drag: function(event, ui) {
        // Calculate the change in left and top positions
        var changeLeft = ui.position.left - ui.originalPosition.left;
        var changeTop = ui.position.top - ui.originalPosition.top;

        // Adjust the new left and top positions by dividing the change by the zoomScale
        var newLeft = ui.originalPosition.left + changeLeft / zoomScale;
        var newTop = ui.originalPosition.top + changeTop / zoomScale;

        // Update the ui.position object with the adjusted values
        ui.position.left = newLeft;
        ui.position.top = newTop;
    }
});

通过使用这些回调处理程序,可拖动和可调整大小的元素现在将在缩放元素内正确运行,而无需修改 jQuery 或实现复杂的修补解决方案。

以上是如何使用 jQuery 的 Draggable() 和 resizing() 插件以及子元素上的 CSS 变换比例?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn