我的jQUery拖拽插件

来源:互联网 发布:哈尔堡工业大学 知乎 编辑:程序博客网 时间:2024/06/03 19:37
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的jQUery拖拽插件</title>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        .drag {
            position: absolute;
        }
        .shape1 {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: #0cc;
        }
        .shape2 {
            top: 200px;
            left: 200px;
            width: 200px;
            height: 100px;
            background: #cc0;
        }
    </style>
</head>
<body>
    <div class="drag shape1"></div>
    <div class="drag shape2"></div>
    <script type="text/javascript">
        $(function() {


            var Drag = function() {
                var $drag = $('.drag');
                var isMove = false;
                var toLeft = 0;
                var toTop = 0;


                return {
                    enable: function() {
                        $drag.bind('mouseover.dragPlugin', function () {
                            $(this).css('cursor', 'move');
                        })
                        .bind('mousedown.dragPlugin', function(e) {
                            isMove = true;
                            // e.pageY相当于dom的e.clientY为鼠标在页面坐标
                            // $x.offset().top相当于dom的x.offsetTop为div距页面天花板距离
                            // 另外 $x.position().top为元素在父元素的定位top
                            toTop = e.pageY - $(this).offset().top; 
                            toLeft = e.pageX - $(this).offset().left;
                        })
                        // 给事件添加命名空间,便于移除事件
                        .bind('mousemove.dragPlugin', function(e) {
                            if (isMove) {
                                console.log('鼠标:',e.pageX,e.pageY);
                                $(this).css({
                                    'top': e.pageY - toTop  + 'px',
                                    'left': e.pageX - toLeft  + 'px'
                                });
                            }
                        })
                        .bind('mouseup.dragPlugin', function() {
                            isMove = false;
                        });
                    },
                    disable: function() {
                        // 移除事件命名空间,就会移除对应所有事件
                        $drag.unbind('.dragPlugin');
                    }
                };
                
            };
            Drag().enable();
            Drag().disable();
            Drag().enable();
            
        }); 
    </script>
</body>
</html>
0 0