23 javascript jquery droppable
任何人都可以告诉我如何在接受条件下编写函数,然后如何找出接受什么和不接受什么.例如,我想接受div a
并div b
接受条件.如何通过函数编写I?
Ale*_*lex 48
If you want the droppable to accept a selection of elements you can do something like this:
$(".droppable").droppable({
accept: function(d) {
if(d.hasClass("foo")||(d.attr("id")=="bar")){
return true;
}
}
});
Run Code Online (Sandbox Code Playgroud)
This droppable will accept elements with the class "foo" or an element with the id "bar"
Bar*_*all 13
如果我正确理解您的问题,您希望根据自定义代码有条件地接受已删除的元素.Aberon的答案是典型的情况:你想只允许某些可拖动的选项根据他们的类被删除,而其他所有选项都将恢复.如果这回答了你的问题,那很好.
但是,有一种情况是根据比类匹配更复杂的事情有条件地进行恢复动画.在我自己的项目中,我使用拖放操作将用户添加到组中.如果被删除的用户已经在组中,我希望用户帮助程序元素还原.否则,我继续使用AJAX操作来插入它们.这不能替代后端检查,但它是很好的视觉反馈.
我已经到别处寻找一个简单的答案.注意JQuery维护者:对我来说,最简单的方法是在drop函数中向事件对象添加一些属性,如下所示:
$('.target').droppable({
accept: '.valid'
drop: function(event, ui) {
if(isDropOK() == true) {
// add child here
} else {
event.revert = true;
}
}
});
Run Code Online (Sandbox Code Playgroud)
可悲的是,这不起作用.下面是"工作"的内容:将可拖动元素设置为始终还原,然后在满足条件时隐藏帮助器.您可以通过查找页面上具有类".ui-draggable-dragging"的唯一元素来获取对帮助程序的引用.这是一个例子,用你自己的逻辑替换"isDropOK()":
$('.valid').draggable({
revert: true,
helper: 'clone',
opacity: 0.5
});
$('.target').droppable({
accept: '.valid'
drop: function(event, ui) {
if(isDropOK() == true) {
$('.ui-draggable-dragging').hide();
// add child here
}
}
});
Run Code Online (Sandbox Code Playgroud)
因此,回顾一下,除非您单步执行drop事件并手动隐藏帮助程序,否则每个元素都将始终还原.还原动画仍会发生,但您的用户将看不到它.这是一个小黑客,但最终的结果似乎没有用.
将接受与选择器匹配的所有可拖动项.如果指定了一个函数,则将为页面上的每个draggable调用该函数(作为函数的第一个参数传递),以提供自定义过滤器.如果应该接受draggable,则该函数应返回true.
从而,
$('.selector').droppable({ accept: '.special' });
Run Code Online (Sandbox Code Playgroud)
在他们的例子中,只有当它具有"特殊"类时,它才会表现得已被删除.看起来它可以接受任何Jquery选择器.
我想补充一下,除了Alex答案(这是我在这个问题上找到的最佳答案)之外,如果您要检查droppable
和之间的匹配属性draggable
,则可以使用关键字this
来访问accept
函数中的droppable 。这是我最近使用的一个小示例:
accept : function (draggable) {
var id_group_drop, id_group_drag;
//get the "id_group" stored in a data-attribute of the draggable
id_group_drag = $(draggable).attr("data-id-group");
//get the "id_group" stored in a data-attribute of the droppable
id_group_drop = $(this).parent().attr("data-id-group");
//compare the id_groups, return true if they match or false otherwise
return id_group_drop == id_group_drag;
}
Run Code Online (Sandbox Code Playgroud)
因此,draggable
只有接受,当它的id_group
(记住,只是一个例子)与相匹配id_group
的droppable
,否则draggable
将被还原。我认为这可能是一个非常常见的用例,也许这会对某人有所帮助。
归档时间: |
|
查看次数: |
42842 次 |
最近记录: |