没有jQuery UI的Draggable div [英] Draggable div without jQuery UI

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

问题描述

正如标题所示,我试图在不使用jQuery UI的情况下制作div。



然而,我被下面的代码弄晕了。我知道我将使用相对于容器div的鼠标位置(其中div将被拖动),并且我将设置相对于这些值的div偏移量。

我无法弄清楚如何。任何线索对我来说?



这段代码不会(当然)工作:

  var X,Y; 

$(this).mousedown(function(){
$(this).offset({
left:X,
top:Y
});
});

$(#containerDiv)。mousemove(function(event){
X = event.pageX;
Y = event.pageY;
});


解决方案

简单的 例子可能让你开始:

$ $ $ $ $ $ $ $ $ $ $ $ $ null;

$(document.body).on(mousemove,function(e){
if($ dragging){
$ dragging.offset({
top:e.pageY,
left:e.pageX
});
}
});


$( (mousedown,div,function(e){
$ dragging = $(e.target);
});

$ (document.body).on(mouseup,function(e){
$ dragging = null;
});
});

示例: http://jsfiddle.net/Jge9z/


据我所知,我应使用相对于容器div的鼠标位置(其中div将被拖动),并且我将设置相对于这些值的div偏移量。

不太确定。在我看来,在拖放操作中,您总是希望使用元素相对于文档的偏移量。



如果您意味着你想限制拖动到特定区域,这是一个更复杂的问题(但仍然可行)。


As the title says I'm trying to make a div draggable without using jQuery UI.

However, I'm stucked with the code below. I understand that I shall use the mouse position relative to the container div (in which the div shall be dragged) and that I shall set the divs offset relative to those values.

I just can't figure out how. Any clues for me?

This code doesn't (of course) work:

var X, Y;

$(this).mousedown(function() {
    $(this).offset({ 
        left: X, 
        top: Y
    });
});

$("#containerDiv").mousemove(function(event) {
    X = event.pageX;
    Y = event.pageY;
});

解决方案

Here's a really simple example that might get you started:

$(document).ready(function() {
    var $dragging = null;

    $(document.body).on("mousemove", function(e) {
        if ($dragging) {
            $dragging.offset({
                top: e.pageY,
                left: e.pageX
            });
        }
    });


    $(document.body).on("mousedown", "div", function (e) {
        $dragging = $(e.target);
    });

    $(document.body).on("mouseup", function (e) {
        $dragging = null;
    });
});

Example: http://jsfiddle.net/Jge9z/

I understand that I shall use the mouse position relative to the container div (in which the div shall be dragged) and that I shall set the divs offset relative to those values.

Not so sure about that. It seems to me that in drag and drop you'd always want to use the offset of the elements relative to the document.

If you mean you want to constrain the dragging to a particular area, that's a more complicated issue (but still doable).

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

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