使用jQuery拖动div [英] Drag div using jquery

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

问题描述

我试图在不使用jQuery UI的情况下使div可拖动.

I'm trying to make a div draggable without using jQuery UI.

HTML

<div class="wrapper">
  <div class="toddler"></div>
</div>

脚本

$.fn.slider = function () {
$(this).on("mousedown", function () {
    $dragging = true;
});

$(this).on("mouseup", function () {
    $dragging = null;
});

$(this).on("mousemove", function () {
    if ($dragging) {
        $(this).offset({
            left: $(this).pageX
        });
    }
});
};

$(".toddler").slider();

我的小提琴

但是我的代码不起作用.怎么了?如何使其工作?

but my code doesn't work. What's wrong? How to make it work?

推荐答案

(function($) {
$.fn.drags = function(opt) {

    opt = $.extend({handle:"",cursor:"move"}, opt);

    if(opt.handle === "") {
        var $el = this;
    } else {
        var $el = this.find(opt.handle);
    }

    return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
        if(opt.handle === "") {
            var $drag = $(this).addClass('draggable');
        } else {
            var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
        }
        var z_idx = $drag.css('z-index'),
            drg_h = $drag.outerHeight(),
            drg_w = $drag.outerWidth(),
            pos_y = $drag.offset().top + drg_h - e.pageY,
            pos_x = $drag.offset().left + drg_w - e.pageX;
        $drag.css('z-index', 1000).parents().on("mousemove", function(e) {
            $('.draggable').offset({
                top:e.pageY + pos_y - drg_h,
                left:e.pageX + pos_x - drg_w
            }).on("mouseup", function() {
                $(this).removeClass('draggable').css('z-index', z_idx);
            });
        });
        e.preventDefault(); // disable selection
    }).on("mouseup", function() {
        if(opt.handle === "") {
            $(this).removeClass('draggable');
        } else {
            $(this).removeClass('active-handle').parent().removeClass('draggable');
        }
    });

}
})(jQuery);

用法:

$('div').drags();

http://css-tricks.com/snippets/jquery /draggable-without-jquery-ui/

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

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