【问题标题】:Set bounds for draggable element设置可拖动元素的边界
【发布时间】:2014-04-28 14:56:34
【问题描述】:
我有一个由 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();
});
});
【问题讨论】:
标签:
jquery
html
jquery-ui
css
【解决方案1】:
您可以添加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
【解决方案2】:
使用遏制来限制它容器
containment: $('#currentimage')
仅供参考
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") }));
});
});