如何制作可投放的div

时间:2012-09-26 14:24:34

标签: jquery drag-and-drop

我创建了一个没有UI或其他插件的可拖动div。但是有一个很大的问题我无法制作可投放的div。这是我的代码:

$(function() {
    $(".dragIt").on("mousedown", function(e) {
        var $dragIt = $(this).addClass('draggable');
        var z_idx = $dragIt.css('z-index'),
            dragHeight = $dragIt.outerHeight(),
            dragWidth = $dragIt.outerWidth(),
            positionY = $dragIt.offset().top + dragHeight - e.pageY,
            positionX = $dragIt.offset().left + dragWidth - e.pageX;
        $dragIt.css('z-index', 1000).parents().on("mousemove", function(e) {
            $('.draggable').offset({
                top: e.pageY + positionY - dragHeight,
                left: e.pageX + positionX - dragWidth
            });
        });
        e.preventDefault();
    }).on("mouseup", function(e) {
        $(this).removeClass('draggable');
    });
});​

我尝试了一些方法,如:

if ( $('.dragIn').position() < $('.dropIn').position() ) {console.log('dropped');}

但它不起作用。有什么解决方案吗?谢谢你的进步!

1 个答案:

答案 0 :(得分:1)

作为一项规则,我不会重新创建功能,除非它更有效。我建议使用UI插件,但这应该会让你走上正确的道路。

请参阅http://jsfiddle.net/sgy9u/7/

HTML:

<div class="dragIt">Draggable</div>
<div class="dropIt">Drop Here</div>

Jquery的:

$(function() {
$(".dragIt").on("mousedown", function(e) {
    var $dragIt = $(this).addClass('draggable');
    var z_idx = $dragIt.css('z-index'),
        dragHeight = $dragIt.outerHeight(),
        dragWidth = $dragIt.outerWidth(),
        positionY = $dragIt.offset().top + dragHeight - e.pageY,
        positionX = $dragIt.offset().left + dragWidth - e.pageX;
    $dragIt.css('z-index', 1000).parents().on("mousemove", function(e) {
        $('.draggable').offset({
            top: e.pageY + positionY - dragHeight,
            left: e.pageX + positionX - dragWidth
        });
    });
    e.preventDefault();
}).on("mouseup", function(e) {
//changes to your code start here
    var dragOff=$('.draggable').offset();
    var off=$('.dropIt').offset();
    var height=$('.dropIt').height();
    var width=$('.dropIt').width();

    //checking the boundaries of dropIt and recording 'dropped' to the console
    if(dragOff.left>=off.left && dragOff.left<=off.left+width
       && dragOff.top>=off.top && dragOff.top <=off.top+height)
        console.log('dropped'); 
//changes to your code end here
    $(this).removeClass('draggable');
});