我的可拖动元素是动态创建的。每次添加项目时,我都会再次调用draggable()。它们有可拖拽的类,但不拖拽。
当编写draggable到调试控制台时,它成功地与非动态元素一起工作。
$(window).on('load', function () {
var item = '<div class="item"></div>';
$field.append(item);
dragItems();
});
function dragItems() {
var $items = $('.item');
$items.draggable();
}在检查器中,我看到创建了drag类,但没有发生移动。
发布于 2019-03-24 01:31:10
考虑下面的例子。
$(function() {
function dragItems(dObj) {
dObj.draggable({
containment: "parent"
});
}
var item = '<div class="item"></div>';
$("#field").append(item);
dragItems($("#field .item"));
});#field {
width: 400px;
height: 200px;
background: #CFC;
}
.item {
width: 100px;
height: 100px;
background: #CCC;
}<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="field"></div>
我怀疑你的例子中还有更多的代码。它被包装在$(function(){});中,它将一直等到document为ready。类似于$(window).on('load')。
该函数被设置为接受jQuery对象并将Draggable赋值给该对象。因此,您必须将$("#field .item")对象传递给它。
现在,如果你先创建了对象,代码可能会少一点。您当前的代码不是创建对象,而是通过append注入HTML字符串。请考虑以下几点。
$(function() {
function dragItems() {
$("#field .item").draggable({
containment: "parent"
});
}
var item = $("<div>", {
class: "item"
});
$("#field").append(item);
dragItems();
});#field {
width: 400px;
height: 200px;
background: #CFC;
}
.item {
width: 100px;
height: 100px;
background: #CCC;
}<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="field"></div>
我认为,这更像是您想要做的事情,您只需将所有.item元素都设置为可拖动即可。您可以使用这两种方法中的任何一种。我只需要确保你创建了一个对象来使用Dragable。
希望这能有所帮助。
https://stackoverflow.com/questions/55313157
复制相似问题