jQuery可拖动问题 [英] Jquery draggable issue

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

问题描述

基本上,我想要的是在拖动时,如果我走出收容区域并在其中释放鼠标单击,则可拖动元素只是停留在我离开收容区域的边界上.当我将光标移回时,该元素会回到光标处.当您只是移动光标(不拖动)而元素仍在拖动时,它看起来并不好.

Basically what I want is that while dragging, if I go outside the containment area and release the mouse click there, the draggable element just sticks to the border from where I left the containement area. And when I move my cursor back in, the element sticks back to the cursor. It doesnt looks nice when you are just moving your cursor(not dragging) and the element is still getting dragged.

此处是一个小玩意儿.只需在输出区域外拖动并释放光标,您就会明白我在说什么.

Here is a fiddle to play with. Just drag and release the cursor outside the output area, you will get what I am talking about.

我在想两种方法

  1. 在拖动鼠标时将鼠标移动到containmenet区域(我进行了搜索,但没有找到方法.也许不可能吗?)

  1. Restrict mouse movement to the containmenet area while being dragged(I searched for it and didnt find how to do it. Mayb thats not possible ?)

如果光标离开容纳区域,则将可拖动对象恢复到其位置. (仍然找不到方法)

Revert the draggable to its position if the cursor leaves the containement area. (Still couldnt find a way to do this)

以任何方式或更明智的方式实现这一目标?

Any way or more bright ideas to achieve this ???

Relevant Code(用于堆栈溢出)

推荐答案

好的,我找到了解决方法.在IE8和Chrome中均可使用.

Ok, I found a workaround for this. Works In IE8 and Chrome.

为可拖动元素添加了此代码.

Added this code for the draggable element.

drag: function(){
     $('body').mouseleave(function(){
          $('body').mouseup();
     });
}

工作小提琴

编辑:感谢 Rembunator 指出了该缺陷,我决定使用.one()以获得更好的性能,并将代码从拖动移到开始

Thanks to Rembunator for pointing out the flaw, I decided to use .one() for better performance, and shift the code from drag to start

start: function(){
     $('body').one("mouseleave", function(){
          $('body').mouseup();
     });
}

最后找到了解决方案.

这是代码:

var flag=true;
start: function( event, ui ){
    if(flag){
         flag = false;
         $('body').one("mouseleave", function(){
             $('body').mouseup();
              flag = true; //event occured, rebind
          });
     }
     else{
         flag = false;
     }
}

感谢 Rembunator 的帮助

这篇关于jQuery可拖动问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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