How to make jQuery draggable with fixed X and Y axis?

前端 未结 5 820
花落未央
花落未央 2020-12-30 09:22

I am wondering if there is a way to make the jQuery draggable to only drag straight up, down and left, right. I want to prevent the user from dragging a div diagonally. Usin

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 10:04

    use the drag event to your advantage

    $('.selector').draggable({
       drag: function(event, ui) { ... }
    });
    

    i'm not 100% sure how, but inside here, you can do a check on the coordinates. as ~jack-laplante said, this is where you would compare. if the coordinates are closer to the x axis than the y, change the axis to x

    //setter
    $('.selector').draggable('option', 'axis', 'x');
    

    if the other way around change it to y. this will get you a snapping motion to always have the item either on the x axis or the y axis (from the starting point). you'd have to do a check to leave the item wherever it is if the axis was say (x+n,y+n), but it would be pretty impressive if someone got more than a few pixels staying on the |x|=|y| line.

    you didn't specify if the axes always remain where they originally started or if they change depending on where the draggable item is on drag start (like if you move it a little bit, then let go, and try to drag it some more). there's a start: and end: event too that could help you with that part.

    what exactly are you trying to drag that can't go diagonal, but can go left, right, up, and down?

提交回复
热议问题