使jQuery可拖动以捕捉到特定的网格

编程入门 行业动态 更新时间:2024-10-18 06:07:10
本文介绍了使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.

jsfiddle/FNhFX/5/

jsfiddle/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可拖动以捕捉到特定的网格

本文发布于:2023-11-25 00:40:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网格   拖动   捉到   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!