元素拖动(外部封装函数)

//调用该函数时传的参数是对象
// 如 :dragable({
//      down:p,        //点击的元素
//      target : div,  //移动的目标元素
//      ranger: div,   //其有定位的父元素
//      moving : function(x,y){   //移动时要执行的函数
//          
//      },
//      ending :function(){        //结束时要执行的函数
//          console.log("拖拽结束");
//      }
//  })

function dragable(options){
    var father=options.ranger||window;//设定其有定位的父元素
    options.down.onmousedown=function(e){

        var e=e||event;         
        var pos={                     
            x:e.offsetX,
            y:e.offsetY
        };
        document.onmousemove=function(e){
            var e=e||event;
            var maxleft=father.offsetWidth||window.innerWidth;
            var maxtop=father.offsetHeight||window.innerHeight;
            var _left=Math.max(0,Math.min(maxleft-options.target.offsetWidth,e.pageX-pos.x-getPagePosition(father).left));
            var _top=Math.max(0,Math.min(maxtop-options.target.offsetHeight,e.pageY-pos.y-getPagePosition(father).top));
            options.target.style.margin="0px";//如果有margin,将margin设为0
            options.target.style.left=_left+"px";
            options.target.style.top=_top+"px";
            options.moving?options.moving(_left,_top):"";

        }
    }
    document.onmouseup=function(){
        document.onmousemove=null;
        options.ending?options.ending():"";
    }
}

//计算元素在页面的绝对位置
function getPagePosition(target){
    var sumleft=target.offsetLeft;
    var sumtop=target.offsetTop;
    while(target.offsetParent != null){
        sumleft+=target.offsetParent.offsetLeft;
        sumtop+=target.offsetParent.offsetTop;
        target=target.offsetParent;
    }
    return {
    left:sumleft,
    top:sumtop
    };
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值