让我的可拖动拼图按网格移动

时间:2014-07-23 11:02:37

标签: jquery grid draggable

我正在使用拖动功能创建更像拼图效果,但我希望我的棋子按100x100 px网格移动,我尝试添加grid: [100,100]但是没有效果。

我用Google搜索并在此处查看了已发布的问题,但找不到任何适合我的解决方案。

这是我的代码:

HTML

<div id="shell">            
    <div class="puzzle">10</div>
    <div class="puzzle">1</div> 
    <div class="puzzle">4</div> 
    <div class="puzzle">7</div> 
    <div class="puzzle">11</div>    
    <div class="puzzle">2</div> 
    <div class="puzzle">5</div> 
    <div class="puzzle">8</div> 
    <div class="puzzle">12</div>    
    <div class="puzzle">6</div> 
    <div class="puzzle">9</div> 
    <div class="puzzle">3</div>            
</div>

的Javascript

(function($) {
    $.fn.drags = function(opt) {

        opt = $.extend({handle:"",cursor:"move"}, opt);

        if(opt.handle === "") {
            var $el = this;
        } else {
            var $el = this.find(opt.handle);
        }

        return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
            if(opt.handle === "") {
                var $drag = $(this).addClass('draggable');
            } else {
                var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
            }
            var z_idx = $drag.css('z-index'),
                drg_h = $drag.outerHeight(),
                drg_w = $drag.outerWidth(),
                pos_y = $drag.offset().top + drg_h - e.pageY,
                pos_x = $drag.offset().left + drg_w - e.pageX;
            $drag.css('z-index', 1000).parents().on("mousemove", function(e) {
                $('.draggable').offset({
                    top:e.pageY + pos_y - drg_h,
                    left:e.pageX + pos_x - drg_w
                }).on("mouseup", function() {
                    $(this).removeClass('draggable').css('z-index', z_idx);
                });
            });
            e.preventDefault(); // disable selection
        }).on("mouseup", function() {
            if(opt.handle === "") {
                $(this).removeClass('draggable');
            } else {
                $(this).removeClass('active-handle').parent().removeClass('draggable');
            }
        });

    }
})(jQuery);
$('.puzzle').drags();

这是jsFidde

1 个答案:

答案 0 :(得分:1)

改为使用sortable

演示:http://jsfiddle.net/lotusgodkk/c797P/5/

JS:

$(document).ready(function () {
    $('#shell').sortable();
});