0

我创建了一个没有 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');}

但它不起作用。有什么解决办法吗?感谢您的提前!

4

1 回答 1

1

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

http://jsfiddle.net/sgy9u/7/

HTML:

<div class="dragIt">Draggable</div>
<div class="dropIt">Drop Here</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) {
//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');
});
于 2012-09-26T17:37:51.170 回答