首頁  >  文章  >  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