jQuery可排序和可拖放 [英] jQuery Sortable and Droppable

查看:85
本文介绍了jQuery可排序和可拖放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可排序的列表,但我也希望该列表中的元素可拖放到我定义为可拖放的div上.我似乎找不到办法.有什么想法吗?

I want to have a list that is sortable, but I also want the elements in that list to be droppable to the divs I have defined as droppable. I can't seem to find a way to do it. Any ideas?

推荐答案

这是Colin解决方案的简化版本.

Here's a simplified version of Colin's solution.

最大的区别是此解决方案不存储可排序元素的整个html,而仅存储当前拖动的项目.如果将物品放在可放置区域,它将被插入到其原始位置.

The biggest difference is that this solution does not store the entire html of the sortable elements, but only the currently dragged item. It is then inserted into it's original position if the item is dropped on the droppable area.

无论如何,这是代码:

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    var dropped = false;
    var draggable_sibling;

    $("#sortable").sortable({
        start: function(event, ui) {
            draggable_sibling = $(ui.item).prev();
        },
        stop: function(event, ui) {
            if (dropped) {
                if (draggable_sibling.length == 0)
                    $('#sortable').prepend(ui.item);

                draggable_sibling.after(ui.item);
                dropped = false;
            }
        }
    });

    $(".droppable").droppable({
        activeClass: 'active',
        hoverClass:'hovered',
        drop:function(event,ui){
            dropped = true;
            $(event.target).addClass('dropped');
        }
    });
});

</script>

<style type="text/css">
#sortable li{
    clear:both;
    float:left;
}

.droppable {
    clear:both;
    height:300px;
    width:400px;
    background-color:#CCC;
}

.droppable.active { background: #CFC; }
.droppable.hovered { background: #CCF; }
.dropped { background: #f52; }
</style>

</head>
<body>

<ul id="sortable">
    <li id="one">One</li>
    <li id="two">Two</li>
    <li id="three">Three</li>
    <li id="four">Four</li>
    <li id="five">Five</li>
    <li id="six">Six</li>
</ul>

<div class="droppable">Drop Here</div>
<div class="droppable">Drop Here</div>

</body>
</html>

如果将项目拖到列表中的新位置,然后放在<ul>和可放置的<div>之外,则仍然遇到与Colin解决方案相同的问题.该项目将不会重置,但会在列表中处于最后位置(在Google Chrome中测试).无论如何,通过鼠标悬停检测可以很容易地解决此问题,甚至可能是令人希望的行为.

It still suffers the same problem as Colin's solution if an item is dragged into a new position in the list and then dropped outside both the <ul> and the droppable <div>. The item will then not reset but take the last position in the list (tested in Google Chrome). Anyway, this is easily solved with some mouse over detection or it may even be desirable behaviour.

这篇关于jQuery可排序和可拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆