javascript jQuery UI Draggable转换比例修复

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript jQuery UI Draggable转换比例修复相关的知识,希望对你有一定的参考价值。

// see fiddle https://jsfiddle.net/gabfusi/femvbz4n/

var _zoom = 1.2,
    $element = $('.draggable-element'),
    $container = $('#container');

var containmentW,
    containmentH,
    objW,
    objH;

$element.draggable({

  start: function(evt, ui) {
    ui.position.left = 0;
    ui.position.top = 0;

    containmentW = $container.width() * _zoom;
    containmentH = $container.height() * _zoom;
    objW = $(this).outerWidth() * _zoom;
    objH = $(this).outerHeight() * _zoom;

  },

  drag: function(evt, ui) {

    var boundReached = false,

        changeLeft = ui.position.left - ui.originalPosition.left,
        newLeft = ui.originalPosition.left + changeLeft / _zoom,

        changeTop = ui.position.top - ui.originalPosition.top,
        newTop = ui.originalPosition.top + changeTop / _zoom;


    // right bound check
    if(ui.position.left > containmentW - objW) {
      newLeft = (containmentW - objW) / _zoom;
      boundReached = true;
    }

    // left bound check
    if(newLeft < 0) {
      newLeft = 0;
      boundReached = true;
    }

    // bottom bound check
    if(ui.position.top > containmentH - objH) {
      newTop = (containmentH - objH) / _zoom;
      boundReached = true;
    }

    // top bound check
    if(newTop < 0) {
      newTop = 0;
      boundReached = true;
    }

    // fix position
    ui.position.left = newLeft;
    ui.position.top = newTop;

    // inside bounds
    if(!boundReached) {

      // do stuff when element is dragged inside bounds

    }

  }
});

以上是关于javascript jQuery UI Draggable转换比例修复的主要内容,如果未能解决你的问题,请参考以下文章

拖放网站生成器javascript库。

jquery-ui-sortable 的拖动事件

jquery.event.drag 和 jquery 可调整大小不兼容

jQuery UI 可拖动位置受 scrollTop 影响? (包括 JSFiddle)

jQuery UI 拖动(Draggable) - 事件

jQuery UI 在悬停时添加可放置的事件侦听器