我有一个可排序的列表,用户可以在其中动态地将项目附加到彼此。在下面的示例中,"Item 3“被附加到"Item 2”。如果两个项目是附加的,我想防止用户在两个项目之间的项目,即在例子中,用户不应该被允许在“项目2”和“项目3”之间的项目。
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li class="attached">Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>有没有允许我控制哪些放置位置的回调?或者,是否有类似于jQuery sortable的不同插件可以提供此功能?
发布于 2011-04-05 19:03:20
jQuery可排序小部件不提供控制允许的拖放区行为的功能。然而,这个问题可以通过将小部件子类化来轻松地解决:
$.widget("ui.custom_list", $.ui.sortable, {
_mouseDrag: function(event) {
// copy this code from the source code of jquery.ui.sortable.js
//Rearrange
for (var i = this.items.length - 1; i >= 0; i--) {
//Cache variables and intersection, continue if no intersection
var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
if (!intersection) continue;
if(itemElement != this.currentItem[0] //cannot intersect with itself
&& this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
&& !$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
// add this line
&& this._allowDropping(itemElement, (intersection == 1 ? "down" : "up"))
//&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
) {
this.direction = intersection == 1 ? "down" : "up";
// Rest of the function
},
_allowDropping: function(itemElement, direction) {
if(this.options.allowDropping) {
return this.options.allowDropping(itemElement, direction);
}
return true;
}
});_mouseDrag函数主要是从可排序的源文件中复制的。唯一的调整是这一行:
&& this._allowDropping(itemElement, (intersection == 1 ? "down" : "up"))然后,可以通过为allowDropping参数提供函数来自定义允许的放置区行为:
$("ul").custom_list({
allowDropping: function(element, direction) {
// element refers to the item that would be moved but not the one being dragged
if(direction == "up") {
...
} else {
...
}
}
})发布于 2011-04-04 20:32:10
您可以有选择地传递一个可排序的items选项,该选项允许您指定希望哪些项目是可排序的。请注意,使用此方法时,您将无法移动项目2和3。
Html
<ul id="list">
<li>Item 1</li>
<li class="attached">Item 2</li>
<li class="attached">Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>JavaScript
$("#sortable").sortable({ items: ':not(.attached)'});希望这能让你走上正轨。下面是一个有效的演示:http://jsfiddle.net/SPPVc/
https://stackoverflow.com/questions/5537832
复制相似问题