另一个可放置的区域

时间:2014-07-29 20:47:27

标签: jquery jquery-ui jquery-ui-draggable jquery-ui-droppable

我有两个可放置的区域,其中一个位于另一个区域内。我希望能够仅针对内部区域捕获掉落事件并防止传播,因此外部根本不会得到它。有可能吗?

<HTML>
<HEAD>
<TITLE>Layout Example</TITLE>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<SCRIPT type="text/javascript">
$(document).ready(function () {
    $('#draggable').draggable();
    $('#droppable1').droppable({
        drop: function() {
            console.log('droppable 1')
        }
    });
    $('#droppable2').droppable({
        drop: function() {
            console.log('droppable 2')
        }
    });
});
</SCRIPT>
<style>
#droppable1 {
    border: 1px solid black;
    position: absolute;
    height: 200px;
    top: 0px;
    width: 500px;
    background: blue;
}
#droppable2 {
    border: 1px solid black;
    position: absolute;
    height: 100px;
    top: 50px;
    width: 400px;
    left: 50px;
    z-index: 100;
    background: red;
}
#draggable {
    border: 1px solid black;
    position: absolute;
    height: 50px;
    top: 300px;
    width: 100px;
    left: 300px;
    z-index: 200;
}
</style>
</HEAD>
<BODY>
<div id="droppable1">Droppable 1</div>

<div id="droppable2">Droppable 2</div>

<div id="draggable">Draggable</div>
</BODY>
</HTML>

这是jsFiddle example

尝试拖动&#39; Draggable&#39;盒子放入&#39; Droppable 2&#39;区域。通过这种实施方式,Droppable 1&#39;区域将首先获得Drop事件,之后它将只会进入Droptable 2&#39;。我想要的只是&#39; Droppable 2&#39;得到这个活动。

1 个答案:

答案 0 :(得分:1)

我不知道为什么事件按此顺序触发,但如果有帮助,这是一个解决方法。只需在触发事件之前设置超时,就可以检查事件冒泡是否完成:

http://jsfiddle.net/BS3g9/3/

$(document).ready(function () {
    $('#draggable').draggable();
    $('#droppable1').droppable({
        drop: function() {
            brain.registerDrop(function() {
               console.log("DROPPED 1!");
            });
        }
    });
    $('#droppable2').droppable({
        drop: function() {
            brain.registerDrop(function() {
               console.log("DROPPED 2!");
            });
        }
    });
});

var brain = {
    state : {
        dropAction : function() {},
        dropTimer : null
    },
    registerDrop  : function(cb) {
        brain.state.dropAction = cb;
        if (brain.state.dropTimer) {
            clearTimeout(brain.state.dropTimer);
        }
        brain.state.dropTimer = setTimeout(function() {
            brain.state.dropAction();
        }, 10);
    }
}