限制 jQuery 可拖动项与同级元素重叠/碰撞 [英] Restrict jQuery draggable items from overlapping/colliding with sibling elements

查看:31
本文介绍了限制 jQuery 可拖动项与同级元素重叠/碰撞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 jQuery UI 来限制可拖动对象的包含区域,并有一些额外的限制.我需要防止可拖动元素与同一容器内的其他元素重叠.我需要允许在moveInHere"区域移动,但不允许在butNotHere"区域移动.可能吗?

<div id="dragMe">

<div id="butNotHere">

<script type="text/javascript">$("#dragMe").draggable({遏制:#moveInHere"});

解决方案

新解决方案

我为此找到了一个名为 JQuery UI Draggable Collision 的插件.使用它,实现您想要的功能变得微不足道.请参阅以下 jsFiddle 示例:http://jsfiddle.net/q3x8w03y/1/(这里使用版本JQuery UI Draggable Collision 的 1.0.2,以及 JQuery 1.7.2 和 JQueryUI 1.1.18.)

代码如下:

$("#dragMe").draggable({障碍:#butNotHere",防止碰撞:真,遏制:#moveInHere"});

旧解决方案

以下应该有效.不过,它有一个小故障.一旦 div 发生碰撞,您必须重新抓取"正在拖动的 div,这可能有点烦人.也许其他人会知道如何解决这个问题.您可以在此处查看我的 jsFiddle 示例:http://jsfiddle.net/MrAdE/8/

var prevOffset, curOffset;$("#dragMe").draggable({拖动:函数(e,ui){prevOffset=curOffset;curOffset= $.extend({},ui.offset);返回真;}});$("#butNotHere").droppable({贪婪:真的,结束:函数(e,ui){ui.helper.offset(curOffset= prevOffset).trigger("mouseup");},宽容:触摸"});

I need to use jQuery UI to restrict the containment area for draggable object with some additional restriction. I need prevent the draggable element from overlapping with other elements within the same container. I need to allow movement in "moveInHere" area but not "butNotHere" area. Is it possible?

<div id="moveInHere">

    <div id="dragMe"> </div>

    <div id="butNotHere"> </div>

</div>


<script type="text/javascript">

    $("#dragMe").draggable({
        containment: "#moveInHere"
    });

</script>

解决方案

Edit: New Solution

I found a plugin for this called JQuery UI Draggable Collision. Using this, implementing your desired functionality becomes trivial. See the following jsFiddle example: http://jsfiddle.net/q3x8w03y/1/ (This uses version 1.0.2 of JQuery UI Draggable Collision, along with JQuery 1.7.2 and JQueryUI 1.1.18.)

Here is the code:

$("#dragMe").draggable({
    obstacle: "#butNotHere",
    preventCollision: true,
    containment: "#moveInHere"
});

Old Solution

The following should work. It has a glitch, though. Once the divs collide, you have to "regrab" the div you are dragging, which can be a little annoying. Perhaps someone else will know how to fix this this. You can see my jsFiddle example here: http://jsfiddle.net/MrAdE/8/

var prevOffset, curOffset;
$("#dragMe").draggable({
    drag: function(e,ui) {
        prevOffset= curOffset;
        curOffset= $.extend({},ui.offset);
        return true;
    }
});

$("#butNotHere").droppable({
    greedy: true,
    over: function(e,ui) {
        ui.helper.offset(curOffset= prevOffset).trigger("mouseup");
    },
    tolerance: "touch"
});​

这篇关于限制 jQuery 可拖动项与同级元素重叠/碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆