admin管理员组

文章数量:1356229

If anyone could help me figure out how to make the draggable elements contained in a div that changes scale based on window size, i'd really appreciate any guidance.

If I do:

element.draggable({ 
    cursor: "move",
    containment: '#container'
});

What will happen is it gives me the containment for the regular size of the container. So if I have a transform: scale(1.5), there will be space in the container that the draggable element can not go.

I've also tried containment: 'parent' but that get's very glitchy.

EDIT

I've found out how to get the top and left containment but I can't figure out how to get the right and bottom.

var containmentArea = $("#container");

containment:  [containmentArea.offset().left, containmentArea.offset().top, ???, ???]

I've tried width and height from containmentArea[0].getBoundingClientRect() but that doesn't seem to be the right move either.


Here is a jsfiddle of some example code.

If anyone could help me figure out how to make the draggable elements contained in a div that changes scale based on window size, i'd really appreciate any guidance.

If I do:

element.draggable({ 
    cursor: "move",
    containment: '#container'
});

What will happen is it gives me the containment for the regular size of the container. So if I have a transform: scale(1.5), there will be space in the container that the draggable element can not go.

I've also tried containment: 'parent' but that get's very glitchy.

EDIT

I've found out how to get the top and left containment but I can't figure out how to get the right and bottom.

var containmentArea = $("#container");

containment:  [containmentArea.offset().left, containmentArea.offset().top, ???, ???]

I've tried width and height from containmentArea[0].getBoundingClientRect() but that doesn't seem to be the right move either.


Here is a jsfiddle of some example code.

Share Improve this question edited Jul 12, 2015 at 18:28 bryan asked Jul 10, 2015 at 17:25 bryanbryan 9,39918 gold badges91 silver badges174 bronze badges 4
  • Not having looked in detail at the dragFix function (possibly, you could restrain the values there instead of using containment), the bounds themselves do appear to work when I tested it, but needed the dragged element dimensions to be subtracted: var bounds = container.getBoundingClientRect(); var dragrect = $('.draggable')[0].getBoundingClientRect() .... containment: [bounds.x,bounds.y, bounds.right - dragrect.width, bounds.bottom - dragrect.height] (fiddle: jsfiddle/z0gqy9w2/4 ) – Me.Name Commented Jul 12, 2015 at 18:57
  • @Me.Name Hmm, the right and bottom seem to work but now the top and left don't. Editing the dragfix could be a possible solution. Good thinking. – bryan Commented Jul 12, 2015 at 19:00
  • Oops, used x and y instead of left and right, x and y work in firefox so had no problems there. This works in Chrome as well (haven't tested ie): containment: [bounds.left,bounds.top, bounds.right - dragrect.width, bounds.bottom - dragrect.height] (jsfiddle/z0gqy9w2/5) (Still, doing the work in dragfix feels more generic, might take a peek at that later on) – Me.Name Commented Jul 13, 2015 at 6:00
  • @Me.Name thanks for taking a crack at this! this doesn't work fully if the draggable container is inside a scrollable container. – bryan Commented Jul 13, 2015 at 12:44
Add a ment  | 

3 Answers 3

Reset to default 6 +50

A version with resetting the coordinates in the drag event (since they were being recalculated already for the scale transformations), without using the containment:

var percent = 1, containmentArea = $("#container");

function dragFix(event, ui) {
    var contWidth = containmentArea.width(), contHeight = containmentArea.height();
    ui.position.left = Math.max(0, Math.min(ui.position.left / percent , contWidth - ui.helper.width()));
    ui.position.top = Math.max(0, Math.min(ui.position.top  / percent,  contHeight- ui.helper.height()));
}

$(".draggable").draggable({
    cursor: "move",
    drag: dragFix,
});

//scaling here (where the percent variable is set too)

Fiddle

In the example width and height of the container are obtained inside the dragevent, you could also store them when scaling for better performance. By having them calculated inside the event, they still work after rescaling, although the percent variable still has to be set. To be truly generic, it could be obtained inside the event as well (and instead of a fixed container, ui.helper.parent() could be used) Since the offset inside the dragevent is (0,0) related to the container (at least it is for the current setup), took the liberty of simplifying originalleft + (position - originalposition)/percent to position / percent Start offset didn't seem to be necessary any more, so left it out in the fiddle, but can be re-added if needed.

Take a look to this :

http://jsfiddle/z0gqy9w2/3/

The edited code is the following one :

    // Matrix regex to take the scale value property of $('#container') element    
    var matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*(-?\d*\.?\d+),\s*0,\s*0\)/,
    matches = $('#container').css('transform').match(matrixRegex);
    // Matches have this value : ["matrix(1.5, 0, 0, 1.5, 0, 0)", "1.5", "1.5"] , so we need matches[1] value :
    var scaleValue = matches[1];
    $(".draggable").draggable({
        cursor: "move",
        start: startFix,
        drag: dragFix,
        containment: [containmentArea.offset().left, containmentArea.offset().top, 
                      ( ( containmentArea.offset().left + ( containmentArea.width() * scaleValue ) ) - ( $(".draggable").width() * scaleValue ) ) ,
                      ( ( containmentArea.offset().top + ( containmentArea.height() * scaleValue ) ) - ( $(".draggable").height()  * scaleValue ) ) ]

    });

As you see, here is the trick :

( ( containmentArea.offset().left + ( containmentArea.width() * scaleValue ) ) - ( $(".draggable").width() * scaleValue ) )

Your right max position will be : The main container left offset + the true width of the container ( with scale ) - the item true width (to let it inside the container).

(Tip: Be free to change the "percent" var value as you want too see the results)

regex ref

Here is my solution:

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

        }

    }
});

Link to fiddle

本文标签: javascriptjquery draggable containment array values for scaled containerStack Overflow