简体   繁体   English

如何使用jquery用鼠标移动div?

[英]How to move div with the mouse using jquery?

I need to be able to move a div with my mouse and store the new pos of the div in database to remember the display. 我需要能够用鼠标移动div并将div的新pos存储在数据库中以记住显示。 How can I do it? 我该怎么做?

I would highly recommend you look into jQuery UI and the draggable interaction. 我强烈建议你研究jQuery UI和可拖动的交互。 Basically, you'll want to add the code to your draggable div (assuming it has id="draggable"): 基本上,您需要将代码添加到可拖动的div中(假设它具有id =“draggable”):

$("#draggable").draggable();

And, then put your necessary behavior in the stop event. 然后,将您的必要行为放在停止事件中。 More specifically, you'd do this: 更具体地说,你这样做:

$('#draggable').draggable({
    stop: function(event, ui) { ... }
});

As for the database storing, you could use an AJAX call in the above function, or you could store it in-page, such that some form-send or other action results in the positional information being passed to the server and stored inline with other data. 至于数据库存储,您可以在上面的函数中使用AJAX调用,或者您可以将其存储在页面中,这样一些表单发送或其他操作会导致位置信息传递到服务器并与其他内联存储数据。 I'd be careful with an AJAX call, since you may bomb your db with position data with every dragging on every browser. 我要小心一个AJAX调用,因为你可能会在每次浏览器上拖动时用位置数据轰炸你的数据库。 Depends on your app... 取决于你的应用程序......

Here is a little jQuery function I just wrote to let you drag divs using only jQuery and not using jQuery UI. 这里有一个小jQuery函数,我刚刚编写,让你只使用jQuery拖动div,而不是使用jQuery UI。

/* PlugTrade.com - jQuery draggit Function */
/* Drag A Div with jQuery */
jQuery.fn.draggit = function (el) {
    var thisdiv = this;
    var thistarget = $(el);
    var relX;
    var relY;
    var targetw = thistarget.width();
    var targeth = thistarget.height();
    var docw;
    var doch;

    thistarget.css('position','absolute');


    thisdiv.bind('mousedown', function(e){
        var pos = $(el).offset();
        var srcX = pos.left;
        var srcY = pos.top;

        docw = $('body').width();
        doch = $('body').height();

        relX = e.pageX - srcX;
        relY = e.pageY - srcY;

        ismousedown = true;
    });

    $(document).bind('mousemove',function(e){ 
        if(ismousedown)
        {
            targetw = thistarget.width();
            targeth = thistarget.height();

            var maxX = docw - targetw - 10;
            var maxY = doch - targeth - 10;

            var mouseX = e.pageX;
            var mouseY = e.pageY;

            var diffX = mouseX - relX;
            var diffY = mouseY - relY;

            // check if we are beyond document bounds ...
            if(diffX < 0)   diffX = 0;
            if(diffY < 0)   diffY = 0;
            if(diffX > maxX) diffX = maxX;
            if(diffY > maxY) diffY = maxY;

            $(el).css('top', (diffY)+'px');
            $(el).css('left', (diffX)+'px');
        }
    });

    $(window).bind('mouseup', function(e){
        ismousedown = false;
    });

    return this;
} // end jQuery draggit function //

The jQuery function even prevents the div from going out of the bounds. jQuery函数甚至可以防止div超出范围。 Basically you attach it to a div that you destine to be the drag activator (say the title bar for instance). 基本上你将它附加到你想要成为拖动激活器的div(例如标题栏)。 Invoking it is as simple as this: 调用它就像这样简单:

$("#titleBar").draggit("#whatToDrag");

So #titleBar would be the id of your titlebar div and #whatToDrag would be the id of what you wanted to drag. 所以#titleBar将是你的标题栏div的id,而#whatToDrag将是你想要拖动的id。 I apologize for the messy code, I just hacked it up and thought it would give you an alternative to jQuery UI, while still making it easy to implement. 我为这个凌乱的代码道歉,我只是把它搞砸了,并认为它会给你一个jQuery UI的替代品,同时还能让它易于实现。

If there are a lot of objects, then mousemove can get expensive. 如果有很多物体,那么鼠标移动会变得昂贵。 A step toward solving it is to bind the handler on mousedown and unbind it on mouseup. 解决它的一步是在mousedown上绑定处理程序并在mouseup上取消绑定它。 This example wasn't written and tested with multiple objects though; 这个例子不是用多个对象编写和测试的; in particular, the current unbinding unbinds everything that was bound before (it can be solved by naming the lambda expression and referring to that name in unbind). 特别是,当前的解绑定取消绑定之前绑定的所有内容(可以通过命名lambda表达式并在unbind中引用该名称来解决)。

jQuery.fn.dragdrop = function (el) {
    this.bind('mousedown', function (e) {
        var relX = e.pageX - $(el).offset().left;
        var relY = e.pageY - $(el).offset().top;
        var maxX = $('body').width() - $(el).width() - 10;
        var maxY = $('body').height() - $(el).height() - 10;
        $(document).bind('mousemove', function (e) {
            var diffX = Math.min(maxX, Math.max(0, e.pageX - relX));
            var diffY = Math.min(maxY, Math.max(0, e.pageY - relY));
            $(el).css('left', diffX + 'px').css('top', diffY + 'px');
        });
    });
    $(window).bind('mouseup', function (e) {
        $(document).unbind('mousemove');
    });
    return this;
};
$(document).ready(function () {
    return $('#obj').dragdrop('#obj');
});

Or in Parenscript: 或者在Parenscript中:

(setf (chain j-query fn dragdrop)                                                                                      
      (lambda (el)                                                                                                     
        (chain this                                                                                                    
               (bind :mousedown                                                                                        
                     (lambda (e)                                                                                       
                       (let ((rel-x (- (chain e page-x) (chain ($ el) (offset) left)))                                 
                             (rel-y (- (chain e page-y) (chain ($ el) (offset) top)))                                  
                             (max-x (- (chain ($ :body) (width)) (chain ($ el) (width)) 10))                           
                             (max-y (- (chain ($ :body) (height)) (chain ($ el) (height)) 10)))                        
                         (chain ($ document)                                                                           
                                (bind :mousemove                                                                       
                                      (lambda (e)                                                                      
                                        (let ((diff-x (min max-x (max 0 (- (chain e page-x) rel-x))))                  
                                              (diff-y (min max-y (max 0 (- (chain e page-y) rel-y)))))                 
                                          (chain ($ el) (css :left (+ diff-x :px)) (css :top  (+ diff-y :px))))))))))) 
        (chain ($ window)                                                                                              
               (bind :mouseup                                                                                          
                     (lambda (e)                                                                                       
                       (chain ($ document)                                                                             
                              (unbind :mousemove)))))                                                                  
        this))                                                                                                         

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM