【问题标题】:Limiting a draggable element within a container限制容器内的可拖动元素
【发布时间】:2012-04-20 01:22:36
【问题描述】:

我在不使用 jquery ui 库的情况下制作了可拖动的 div,但我想制作可拖动的框,而不是离开它的容器。

这是我的demo

$(document).ready(function() {
    var $dragging = null;

    $(document.body).on("mousemove", function(e) {
        if ($dragging) {
            $dragging.offset({
                top: e.pageY,
                left: e.pageX
            });
        }
    });

    $(document.body).on("mousedown", ".box", function (e) {
        $dragging = $(e.target);
    });

    $(document.body).on("mouseup", function (e) {
        $dragging = null;
    });
});​

如何做到这一点?请注意,我没有使用 JQUERY UI

【问题讨论】:

    标签: jquery draggable droppable


    【解决方案1】:

    只要确保...

    • 框的左侧位置大于容器的左侧位置,并且
    • 盒子右侧位置(左侧位置+盒子宽度)小于容器右侧位置,且
    • 盒子的顶部位置大于容器的顶部位置,并且
    • 盒子底部位置(顶部位置+盒子高度)小于容器底部位置

    http://jsfiddle.net/KdehU/2/

    $(document).ready(function() {
        var $dragging = null;
    
        var container = $('#container'),
            c_t = container.offset().top,
            c_l = container.offset().left,
            c_b = c_t + container.height(),
            c_r = c_l + container.width();
    
        $(document.body).on("mousemove", function(e) {
            if ($dragging) {
                var width = $dragging.width();
                var height = $dragging.height();
    
                var new_y = (e.pageY > c_t && (e.pageY + height) < c_b) ? e.pageY : undefined;
                var new_x = (e.pageX > c_l && (e.pageX + width) < c_r) ? e.pageX : undefined;
    
                $dragging.offset({
                    top: new_y,
                    left: new_x
                });
            }
        });
    
        $(document.body).on("mousedown", ".box", function (e) {
            $dragging = $(e.target);
        });
    
        $(document.body).on("mouseup", function (e) {
            $dragging = null;
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-06
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      相关资源
      最近更新 更多