jQuery UI Draggable + CSS Transform Causes “Jumping”

后端 未结 6 1186
既然无缘
既然无缘 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:45

    Here is a working example showing raghugolconda's method.

    I utilized the data method, instead of setting non-standard attr values.

    I wrapped it all into a jQuery plugin called $.fn.draggablePatched.

    function main() {
      $('#draggable').draggablePatched({
        cursor: 'pointer'
      });
    }
    
    /* jquery.draggable-patched.js */
    (function($) {
      var __dx, __dy;
      var __recoupLeft, __recoupTop;
    
      var parseIntSafe = function(value) {
        return (function(n) {
          return isNaN(n) ? 0 : n;
        })(parseInt(value, 10));
      }
    
      $.fn.draggablePatched = function(options) {
        options = options || {};
        return this.draggable({
          cursor: options.cursor || 'move',
          zIndex: 100,
          drag: function(event, ui) {
            __dx = ui.position.left - ui.originalPosition.left;
            __dy = ui.position.top - ui.originalPosition.top;
            ui.position.left = ui.originalPosition.left + __dx + __recoupLeft;
            ui.position.top = ui.originalPosition.top + __dy + __recoupTop;
            if (options.drag) {
              options.drag(event, ui);
            }
          },
          start: function(event, ui) {
            var left = parseIntSafe($(this).css('left'));
            var top = parseIntSafe($(this).css('top'));
            __recoupLeft = left - ui.position.left;
            __recoupTop = top - ui.position.top;
            if (options.start) {
              options.start(event, ui);
            }
          },
          stop: function(event, ui) {
            $(this).animate({
              left: $(this).data('oriLeft'),
              top: $(this).data('oriTop')
            }, 1000);
            if (options.stop) {
              options.stop(event, ui);
            }
          },
          create: function(event, ui) {
            $(this).data({
              oriLeft: $(this).css('left'),
              oriTop: $(this).css('top')
            });
            if (options.create) {
              options.create(event, ui);
            }
          }
        });
      }
    })(jQuery);
    
    main();
    body {
      background-color: blue;
    }
    
    #draggable {
      position: absolute;
      left: 50px;
      top: 50px;
      width: 350px;
      height: 350px;
      
      background-color: rgba(0, 0, 0, 0.5);
      border: 1px solid black;
      color: white;
      
      font-size: 4em;
      line-height: 350px;
      text-align: center;
      
      -moz-transform: rotate(-45deg) scale(0.5);
      -webkit-transform: rotate(-45deg) scale(0.5);
      transform: rotate(-45deg) scale(0.5);
    }
    
    
    
    Hello!

提交回复
热议问题