使jQuery可拖动以捕捉到特定的网格 [英] Getting jQuery draggable to snap to specific grid

查看:168
本文介绍了使jQuery可拖动以捕捉到特定的网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(注意: 有些人问过类似的问题,但太具体了,没有给出可用的答案)

jQuery UI的可拖动小部件具有用于捕捉到网格的选项,但是无法设置网格的相对位置.

jQuery UI's draggable widget has options for snapping to a grid, but no way to set what the grid is relative to.

例如,在放置目标中我们已经明确定义了20x20的网格.在放置目标内从0,0开始的拖动项将与网格对齐.但是,从其他位置开始或在放置目标之外的拖动项目不会与该网格对齐.

For example, we've got a clearly defined 20x20 grid in our drop target. A drag item that starts at 0,0 within the drop target will snap in correspondence with the grid. But a drag item that starts at a different location, or outside the drop target, will not line up with that grid.

http://jsfiddle.net/FNhFX/5/

http://jsfiddle.net/FNhFX/5/

HTML:

<div class="drop-target">
    <div class="drag-item">Drag me</div>
    <div class="drag-item" style="left:87px;top:87px;">Drag me</div>
</div>
<div class="outside-drag-item">Drag me</div>

JS:

$(function() {
    $(".drag-item").draggable({
        grid: [20, 20]
    });
    $(".outside-drag-item").draggable({
        grid: [20, 20],
        helper:"clone"
    });
    $(".drop-target").droppable({
        accept: ".drag-item"
    });
});

是否有任何使用jQuery可拖动的方法捕捉到特定网格?

Is there any way to snap to a specific grid using jQuery draggable?

推荐答案

我也将继续在此处发布答案,尽管我是通过

I'm going to go ahead and post an answer here, too, though I came here via a followup question you asked.

您可以在可拖动的jQuery UI的drag事件中非常轻松地创建自己的捕捉到网格功能.

You can create your own snap-to-grid functionality very easily inside the drag event on a jQuery UI draggable.

基本上,您想检查当前ui位置在可拖动对象被拖动到网格上的任何时候有多近.该接近度始终可以表示为该位置的其余部分除以网格.如果该余数小于或等于snapTolerance,则只需将位置设置为没有该余数的位置即可.

Basically, you want to check how close the current ui position is at any point that the draggable is being dragged to a grid. That proximity can always be represented as the remainder of the position divided by the grid. If that remainder is less than or equal to the snapTolerance, then just set the position to what it would be without that remainder.

用散文说那很奇怪.在代码中应该更清楚:

That was weird to say in prose. In the code it should be more clear:

实时演示

// Custom grid
$('#box-3').draggable({
    drag: function( event, ui ) {
        var snapTolerance = $(this).draggable('option', 'snapTolerance');
        var topRemainder = ui.position.top % 20;
        var leftRemainder = ui.position.left % 20;

        if (topRemainder <= snapTolerance) {
            ui.position.top = ui.position.top - topRemainder;
        }

        if (leftRemainder <= snapTolerance) {
            ui.position.left = ui.position.left - leftRemainder;
        }
    }  
});

这篇关于使jQuery可拖动以捕捉到特定的网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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