设置draggable元素的边界

时间:2014-03-21 09:53:35

标签: jquery html css jquery-ui css3

我有一个由jQuery动态生成的可拖动元素。我在div中有一个背景图片。如何绑定元素,使它永远不会超出div?

以下是代码:jsfiddle.net

$(document).ready(function () {
    $("button").click(function () {
        $("#currentimage").append('<img id="dragable" src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />');
        $("#dragable").draggable();
    });
});

2 个答案:

答案 0 :(得分:2)

您可以添加containment: 'parent'。您还必须添加类dragable而不是id。 Id必须是唯一的。这样您就可以多次单击该按钮。

尝试:

$(document).ready(function () {
    $("button").click(function () {
        $("#currentimage").append('<img class="dragable" src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />');
        $(".dragable").draggable({
        containment: 'parent' 
        });         
    });
});

DEMO

答案 1 :(得分:1)

使用包含限制容器

containment: $('#currentimage')

<强> FYI

ID必须是唯一的

.append('<img id="dragable"

阅读Two HTML elements with same id attribute: How bad is it really?

您正在添加具有相同ID的图片。

<小时/> 您可以使用班级

.append('<img class="dragable"

比使用

$(".dragable").draggable();

<小时/> Fiddle Demo

$(document).ready(function () {
    $("button").click(function () {
        var el = '<img src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />';
        $("#currentimage").append($(el).draggable({ containment: $("#currentimage") }));
    });
});