在父元素范围内任意拖动子元素位置

上一个小demo,稍后有空会上传一个自己写的长图合成工具,里面也有这个小demo的运用


function small_down(e) {

var obig = document.getElementById("big");

var osmall = document.getElementById("small");

var e = e || window.event;

/*用于保存小的div拖拽前的坐标*/

        osmall.startX = e.clientX - osmall.offsetLeft;

osmall.startY = e.clientY - osmall.offsetTop;

/*鼠标的移动事件*/

        document.onmousemove = function (e) {

var e = e || window.event;

osmall.style.left = e.clientX - osmall.startX + "px";

osmall.style.top = e.clientY - osmall.startY + "px";

/*对于大的DIV四个边界的判断*/

            if (e.clientX - osmall.startX <= 0) {

osmall.style.left = 0 + "px";

}

if (e.clientY - osmall.startY <= 0) {

osmall.style.top = 0 + "px";

}

if (e.clientX - osmall.startX >= 250) {

osmall.style.left = 250 + "px";

}

if (e.clientY - osmall.startY >= 250) {

osmall.style.top = 250 + "px";

}

};

/*鼠标的抬起事件,终止拖动*/

        document.onmouseup = function () {

document.onmousemove = null;

document.onmouseup = null;

};

}


     

     


#big {

margin:100px;

border:1px solid #FF3300;

width:300px;

height:300px;

position:relative;

}

#small {

background:#99CC00;

width:50px;

height:50px;

position:absolute;

cursor:pointer;

}

你可能感兴趣的:(在父元素范围内任意拖动子元素位置)