2

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

这是我的演示

$(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

4

1 回答 1

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;
    });
});
于 2012-04-20T02:07:47.473 回答