jquery 拖拽插件

来源:互联网 发布:如何阻止windows更新 编辑:程序博客网 时间:2024/05/21 15:02

2010-05-27 14:38:58|  分类:javascript |  标签:|字号 订阅

JS代码:

/**
* drag for jQuery
*
* author: harry313
* e-mail:
*
* Version: 1.0.0
*/
(function($) {
    $.fn.draggable = function(opts) {

        //默认参数设置
        var defaultSettings = {
            parent: document,                //父级容器
            target: this,                    //拖拽时移动的对象
            onmove: function(e) {            //拖拽处理函数
                $(settings.target).css({
                    left: e.clientX - dx,
                    top: e.clientY - dy
                });
            },
            onfinish: function(){}            //拖拽完成回调函数
        };

        var settings = $.extend({}, defaultSettings, opts);

        var dx, dy, moveout;

        //防止拖拽时选中文本
        this.bind("selectstart", function(){return false;});

        //鼠标按下时记录鼠标相对位置
        this.mousedown(function(e) {
            var t = $(settings.target);
            dx = e.clientX - parseInt(t.css("left"));
            dy = e.clientY - parseInt(t.css("top"));

            $(settings.parent).mousemove(move).mouseout(out);

            $().mouseup(up);
        });

        //鼠标在父级容器上移动时的处理
        function move(e) {
            moveout = false;
            settings.onmove(e);
        }

        //鼠标移出父级容器时的处理
        function out(e) {
            moveout = true;
            setTimeout(function(){checkout(e);}, 100);    //微调
        }

        //拖拽结束
        function up(e) {
            $(settings.parent).unbind("mousemove", move).unbind("mouseout", out);
            $().unbind("mouseup", up);
            settings.onfinish(e);
        }
        function checkout(e) {
            moveout && up(e);
        }
    };


})(jQuery);

 

HTML代码:

<script src="jquery.js"></script><!--jquery 插件所在位置-->
<script src="pub.js"></script><!--插件所在文件-->


<script type="text/javascript">
$(function() {
    $("#k2").draggable();
 $("#k1").draggable();
});
</script>
<style type="text/css">
div#k2 {
    position: absolute;
    left: 0px;
    top: 0px;
    border: 1px solid;
    width: 200px;
    height: 100px;
    background-color: blue;
}
</style>

<div id="k1">111</div>
<div id="k2">222</div>


原创粉丝点击