使用jquery实现简单的拖动效果,分享源码

因为想实现相框的拖到,找了半天的原因愣是没有找到错误,所以,只能翻看源码了

如何实现拖动效果?

浏览DEMO

首先分析下拖动效果原理:

1.当鼠标在被拖动对象上按下鼠标(触发onmousedown事件,且鼠标在对象上方)

2.开始移动鼠标(触发onmousemove事件)

3.移动时更显对象的top和left值

4.鼠标放开停止拖动(触发onmouseup事件)

注意:拖动的对象必须是定位对象(即设置了position:absolute或 relative)。

也就是说拖动事件=onmousedown事件+onmousemove事件

整个过程就是处理这三个事件来模拟drag事件

现在看看我实现的源代码:

html代码:

<div class="drag">
  <p class="title">标题(点击标题拖动)</p>
</div>

<div class="drag1">
  <p class="title">标题</p>
  点击我移动
</div>

jquery插件代码:

(function($){
    $.fn.drag=function(options){

    //默认配置
    var defaults = {
        handler:false,
        opacity:0.5
        };

       // 覆盖默认配置
    var opts = $.extend(defaults, options);

    this.each(function(){

    //初始标记变量
    var isMove=false,
    //handler如果没有设置任何值,则默认为移动对象本身,否则为所设置的handler值
    handler=opts.handler?$(this).find(opts.handler):$(this),
    _this=$(this), //移动的对象
    dx,dy;

    $(document)
    //移动鼠标,改变对象位置
    .mousemove(function(event){
    // console.log(isMove);
    if(isMove){

      //获得鼠标移动后位置
    var eX=event.pageX,eY=event.pageY;

    //更新对象坐标
     _this.css({'left':eX-dx,'top':eY-dy});

            }
        })

    //当放开鼠标,停止拖动
    .mouseup(function(){
        isMove=false;
        _this.fadeTo('fast', 1);
        //console.log(isMove);
            });

    handler
    //当按下鼠标,设置标记变量isMouseDown为true
    .mousedown(function(event){

    //判断最后触发事件的对象是否是handler
    if($(event.target).is(handler)){

        isMove=true;
        $(this).css('cursor','move');

        //console.log(isMove);
        _this.fadeTo('fast', opts.opacity);

        //鼠标相对于移动对象的坐标
        dx=event.pageX-parseInt(_this.css("left"));
        dy=event.pageY-parseInt(_this.css("top"));

            }
                 });
         });
    };
 })(jQuery);

调用方法:

  $(function(){

  //拖动标题
  $(".drag").drag({
handler:$('.title'),//操作拖动的对象,此对象必须是移动对象的子元素
opacity:0.7 //设置拖动时透明度
});

  //拖动主体对象
  $(".drag1").drag({
 opacity:0.7
 });

  });

表明:参考http://www.muzilei.com/文章,太赞了!

 

posted @ 2016-08-09 22:46  我当道士那儿些年  阅读(1042)  评论(0编辑  收藏  举报