最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set axis depending draggable direction jQuery draggable - Stack Overflow

programmeradmin3浏览0评论

How can the axis be set depending it's draggable direction (after init)?

If it's dragged left-right it will be x, y if dragged up-down.

$("#belt").draggable({
    handle: "li",
    axis: "y",
    start: function() {

        //I want to be dragged in the axis i belong which should be x....

    },
});

How can the axis be set depending it's draggable direction (after init)?

If it's dragged left-right it will be x, y if dragged up-down.

$("#belt").draggable({
    handle: "li",
    axis: "y",
    start: function() {

        //I want to be dragged in the axis i belong which should be x....

    },
});
Share Improve this question edited Mar 2, 2012 at 2:14 Codex73 asked Mar 2, 2012 at 2:03 Codex73Codex73 5,77613 gold badges58 silver badges77 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You use distance to constrain the motion initially to get the initial read of which direction the user is moving and then set the axis limitation.

var x, y;

$("#belt").draggable({
    start: function(event) {
        x = event.originalEvent.pageX;
        y = event.originalEvent.pageY;
    }, 
    drag: function(event) {
        if (x && y) {
            axis = Math.abs(event.originalEvent.pageX - x) > Math.abs(event.originalEvent.pageY - y) ? 'x' : 'y';
            $("#belt").draggable('option', 'axis', axis);
            x = y = null;
        }        
    },
    stop: function() {
        x = y = null;
        $("#belt").draggable('option', 'axis', false);
    },
    distance: 20
});​

Here's a fiddle: http://jsfiddle/jhchen/B7J2E/

Appreciate the answer jhchen! I forked your fiddle to include some code so that the axis locking happens only when the user presses and holds the shift key while dragging.

http://jsfiddle/B7J2E/40/

var x, y;

$("#test").draggable({
    start: function(event) {
        console.log(event);
        x = event.originalEvent.pageX;
        y = event.originalEvent.pageY;
        console.log(x, y);
    }, 
    drag: function(event) {
        if (event.shiftKey) { 
            if (x && y) {
                axis = Math.abs(event.originalEvent.pageX - x) > Math.abs(event.originalEvent.pageY - y) ? 'x' : 'y';
                $("#test").draggable('option', 'axis', axis);
                x = y = null;
            }        
        }
    },
    stop: function() {
        x = y = null;
        $("#test").draggable('option', 'axis', false);
    },
    distance: 20
});
发布评论

评论列表(0)

  1. 暂无评论