Webkit和jQuery draggable jump

gob*_*k88 36 javascript jquery webkit css3

作为一个实验,我创建了一些div并使用CSS3旋转它们.

    .items { 
        position: absolute;
        cursor: pointer;
        background: #FFC400;
        -moz-box-shadow: 0px 0px 2px #E39900;
        -webkit-box-shadow: 1px 1px 2px #E39900; 
        box-shadow: 0px 0px 2px #E39900;
        -moz-border-radius: 2px; 
        -webkit-border-radius: 2px;
        border-radius: 2px;
    }
Run Code Online (Sandbox Code Playgroud)

然后我随机设置它们并通过jQuery使它们可拖动.

    $('.items').each(function() {
        $(this).css({
            top: (80 * Math.random()) + '%',
            left: (80 * Math.random()) + '%',
            width: (100 + 200 * Math.random()) + 'px',
            height: (10 + 10 * Math.random()) + 'px',
            '-moz-transform': 'rotate(' + (180 * Math.random()) + 'deg)',
            '-o-transform': 'rotate(' + (180 * Math.random()) + 'deg)',
            '-webkit-transform': 'rotate(' + (180 * Math.random()) + 'deg)',
        });
    });

    $('.items').draggable();
Run Code Online (Sandbox Code Playgroud)

拖动工作,但我注意到只在webkit浏览器中拖动div时突然跳转,而Firefox中的一切都很好.

如果我删除位置:绝对风格,"跳跃"甚至更糟.我认为webkit和gecko之间的转换起源可能存在差异,但默认情况下它们都位于元素的中心.

我已经搜索过了,但只提出了有关滚动条或可排序列表的结果.

这是我的问题的工作演示.尝试在Safari/Chrome和Firefox中查看它.http://jsbin.com/ucehu/

这是webkit中的错误还是浏览器如何呈现webkit?

Dav*_*ick 34

这是draggable依赖于jquery offset()函数和offset()使用本机js函数的结果getBoundingClientRect().最终这是一个问题,jquery核心无法弥补与之相关的不一致性getBoundingClientRect().Firefox的版本getBoundingClientRect()忽略了css3转换(旋转),而chrome/safari(webkit)则没有.

是一个问题的例证.

一个hacky解决方法:

jquery.ui.draggable.js中替换以下内容


//The element's absolute position on the page minus margins
this.offset = this.positionAbs = this.element.offset();
Run Code Online (Sandbox Code Playgroud)


//The element's absolute position on the page minus margins
this.offset = this.positionAbs = { top: this.element[0].offsetTop, 
                                   left: this.element[0].offsetLeft };
Run Code Online (Sandbox Code Playgroud)

最后是你的jsbin的monkeypatched版本.


Lia*_*Kai 32

在@David Wick的回答中,我在不同浏览器上旋转后绘制图像以指示偏移量.

旋转后偏移

如果您不想修补或修改jquery.ui.draggable.js,这是要修复的代码

$(document).ready(function () {
    var recoupLeft, recoupTop;
    $('#box').draggable({
        start: function (event, ui) {
            var left = parseInt($(this).css('left'),10);
            left = isNaN(left) ? 0 : left;
            var top = parseInt($(this).css('top'),10);
            top = isNaN(top) ? 0 : top;
            recoupLeft = left - ui.position.left;
            recoupTop = top - ui.position.top;
        },
        drag: function (event, ui) {
            ui.position.left += recoupLeft;
            ui.position.top += recoupTop;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

或者你可以看到演示

  • 真棒和+1不必修改任何jQuery代码. (2认同)

ecm*_*aut 21

David Wick对于上面的总体方向是正确的,但计算正确的坐标比这更为复杂.这是一个更准确的猴子补丁,基于MIT许可的Firebug代码,它应该适用于你有一个复杂DOM的更多情况:

而是替换:

    //The element's absolute position on the page minus margins
    this.offset = this.positionAbs = this.element.offset();

不那么hacky(一定要得到整个东西;你需要滚动):

    //The element's absolute position on the page minus margins
    this.offset = this.positionAbs = getViewOffset(this.element[0]);

    function getViewOffset(node) {
      var x = 0, y = 0, win = node.ownerDocument.defaultView || window;
      if (node) addOffset(node);
      return { left: x, top: y };

      function getStyle(node) {
        return node.currentStyle || // IE
               win.getComputedStyle(node, '');
      }

      function addOffset(node) {
        var p = node.offsetParent, style, X, Y;
        x += parseInt(node.offsetLeft, 10) || 0;
        y += parseInt(node.offsetTop, 10) || 0;

        if (p) {
          x -= parseInt(p.scrollLeft, 10) || 0;
          y -= parseInt(p.scrollTop, 10) || 0;

          if (p.nodeType == 1) {
            var parentStyle = getStyle(p)
              , localName   = p.localName
              , parent      = node.parentNode;
            if (parentStyle.position != 'static') {
              x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
              y += parseInt(parentStyle.borderTopWidth, 10) || 0;

              if (localName == 'TABLE') {
                x += parseInt(parentStyle.paddingLeft, 10) || 0;
                y += parseInt(parentStyle.paddingTop, 10) || 0;
              }
              else if (localName == 'BODY') {
                style = getStyle(node);
                x += parseInt(style.marginLeft, 10) || 0;
                y += parseInt(style.marginTop, 10) || 0;
              }
            }
            else if (localName == 'BODY') {
              x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
              y += parseInt(parentStyle.borderTopWidth, 10) || 0;
            }

            while (p != parent) {
              x -= parseInt(parent.scrollLeft, 10) || 0;
              y -= parseInt(parent.scrollTop, 10) || 0;
              parent = parent.parentNode;
            }
            addOffset(p);
          }
        }
        else {
          if (node.localName == 'BODY') {
            style = getStyle(node);
            x += parseInt(style.borderLeftWidth, 10) || 0;
            y += parseInt(style.borderTopWidth, 10) || 0;

            var htmlStyle = getStyle(node.parentNode);
            x -= parseInt(htmlStyle.paddingLeft, 10) || 0;
            y -= parseInt(htmlStyle.paddingTop, 10) || 0;
          }

          if ((X = node.scrollLeft)) x += parseInt(X, 10) || 0;
          if ((Y = node.scrollTop))  y += parseInt(Y, 10) || 0;
        }
      }
    }

遗憾的是,DOM本身并没有公开这些计算.


小智 11

@ecmanaut:很棒的解决方案.谢谢你的努力.为了帮助别人,我把你的解决方案变成了一个猴子补丁.将下面的代码复制到文件中.加载jquery-ui.js后包含文件如下:

<script src="javascripts/jquery/jquery.js"></script>
<script src="javascripts/jquery/jquery-ui.js"></script>

<!-- the file containing the monkey-patch to draggable -->
<script src="javascripts/jquery/patch_draggable.js"></script>
Run Code Online (Sandbox Code Playgroud)

这是复制/粘贴到patch_draggable.js的代码:

function monkeyPatch_mouseStart() {
     // don't really need this, but in case I did, I could store it and chain
     var oldFn = $.ui.draggable.prototype._mouseStart ;
     $.ui.draggable.prototype._mouseStart = function(event) {

            var o = this.options;

           function getViewOffset(node) {
              var x = 0, y = 0, win = node.ownerDocument.defaultView || window;
              if (node) addOffset(node);
              return { left: x, top: y };

              function getStyle(node) {
                return node.currentStyle || // IE
                       win.getComputedStyle(node, '');
              }

              function addOffset(node) {
                var p = node.offsetParent, style, X, Y;
                x += parseInt(node.offsetLeft, 10) || 0;
                y += parseInt(node.offsetTop, 10) || 0;

                if (p) {
                  x -= parseInt(p.scrollLeft, 10) || 0;
                  y -= parseInt(p.scrollTop, 10) || 0;

                  if (p.nodeType == 1) {
                    var parentStyle = getStyle(p)
                      , localName   = p.localName
                      , parent      = node.parentNode;
                    if (parentStyle.position != 'static') {
                      x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
                      y += parseInt(parentStyle.borderTopWidth, 10) || 0;

                      if (localName == 'TABLE') {
                        x += parseInt(parentStyle.paddingLeft, 10) || 0;
                        y += parseInt(parentStyle.paddingTop, 10) || 0;
                      }
                      else if (localName == 'BODY') {
                        style = getStyle(node);
                        x += parseInt(style.marginLeft, 10) || 0;
                        y += parseInt(style.marginTop, 10) || 0;
                      }
                    }
                    else if (localName == 'BODY') {
                      x += parseInt(parentStyle.borderLeftWidth, 10) || 0;
                      y += parseInt(parentStyle.borderTopWidth, 10) || 0;
                    }

                    while (p != parent) {
                      x -= parseInt(parent.scrollLeft, 10) || 0;
                      y -= parseInt(parent.scrollTop, 10) || 0;
                      parent = parent.parentNode;
                    }
                    addOffset(p);
                  }
                }
                else {
                  if (node.localName == 'BODY') {
                    style = getStyle(node);
                    x += parseInt(style.borderLeftWidth, 10) || 0;
                    y += parseInt(style.borderTopWidth, 10) || 0;

                    var htmlStyle = getStyle(node.parentNode);
                    x -= parseInt(htmlStyle.paddingLeft, 10) || 0;
                    y -= parseInt(htmlStyle.paddingTop, 10) || 0;
                  }

                  if ((X = node.scrollLeft)) x += parseInt(X, 10) || 0;
                  if ((Y = node.scrollTop))  y += parseInt(Y, 10) || 0;
                }
              }
            }


                //Create and append the visible helper
                this.helper = this._createHelper(event);

                //Cache the helper size
                this._cacheHelperProportions();

                //If ddmanager is used for droppables, set the global draggable
                if($.ui.ddmanager)
                    $.ui.ddmanager.current = this;

                /*
                 * - Position generation -
                 * This block generates everything position related - it's the core of draggables.
                 */

                //Cache the margins of the original element
                this._cacheMargins();

                //Store the helper's css position
                this.cssPosition = this.helper.css("position");
                this.scrollParent = this.helper.scrollParent();

                //The element's absolute position on the page minus margins
            this.offset = this.positionAbs = getViewOffset(this.element[0]);
                this.offset = {
                    top: this.offset.top - this.margins.top,
                    left: this.offset.left - this.margins.left
                };

                $.extend(this.offset, {
                    click: { //Where the click happened, relative to the element
                        left: event.pageX - this.offset.left,
                        top: event.pageY - this.offset.top
                    },
                    parent: this._getParentOffset(),
                    relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
                });

                //Generate the original position
                this.originalPosition = this.position = this._generatePosition(event);
                this.originalPageX = event.pageX;
                this.originalPageY = event.pageY;

                //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
                (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

                //Set a containment if given in the options
                if(o.containment)
                    this._setContainment();

                //Trigger event + callbacks
                if(this._trigger("start", event) === false) {
                    this._clear();
                    return false;
                }

                //Recache the helper size
                this._cacheHelperProportions();

                //Prepare the droppable offsets
                if ($.ui.ddmanager && !o.dropBehaviour)
                    $.ui.ddmanager.prepareOffsets(this, event);

                this.helper.addClass("ui-draggable-dragging");
                //JWL: Hier vindt de jump plaats
                this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

                //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
                if ( $.ui.ddmanager ) $.ui.ddmanager.dragStart(this, event);

                return true;

     };

 }
monkeyPatch_mouseStart();
Run Code Online (Sandbox Code Playgroud)

  • 我收到一个错误:Uncaught TypeError:无法读取未定义的jquery-ui.js的属性'offset':1298 (3认同)

UnL*_*oCo 6

我更喜欢这种解决方法,因为它保留了原始处理程序,
它删除了转换然后恢复了它。

$(document).ready(function(){

    // backup original handler
    var _mouseStart = $.ui.draggable.prototype._mouseStart;

    $.ui.draggable.prototype._mouseStart = function(event) {

        //remove the transform
        var transform = this.element.css('transform');
        this.element.css('transform', 'none');

        // call original handler
        var result = _mouseStart.call(this, event);

        //restore the transform
        this.element.css('transform', transform);

        return result;
    };
});
Run Code Online (Sandbox Code Playgroud)

演示(从@廖三开jsbin开始)


小智 5

David Wick的答案非常有用......谢谢......这里我为resizeable编写了相同的解决方法,因为它有同样的问题:

jquery.ui.resizable.js中搜索以下内容

var o = this.options, iniPos = this.element.position(), el = this.element;
Run Code Online (Sandbox Code Playgroud)

并替换为:

var o = this.options, iniPos = {top:this.element[0].offsetTop,left:this.element[0].offsetLeft}, el = this.element;
Run Code Online (Sandbox Code Playgroud)