按住移动元素

只写了x轴的。

<script type="text/javascript">
function getScroll(){
x=window.pageXOffset || (document.body.scrollLeft+document.documentElement.scrollLeft);
console.log("scrollx:",x);
return {
scrollx:x
}
}

function drag(targetToElment,e){

var scrollx=getScroll().scrollx;
var startx=e.clientX+scrollx;
var origx=targetToElment.offsetLeft;

var mouse_zsj_x=startx-origx;
var moveHandler=function(event){
targetToElment.style.left=(event.clientX+getScroll().scrollx-mouse_zsj_x)+"px";
if(e.stopPropagation){
e.stopPropagation();
}
};
var upHandler=function(event){
document.removeEventListener("mousemove",moveHandler,true);
document.removeEventListener("mouseup",upHandler,true);
if(e.stopPropagation){
e.stopPropagation();
}
};


if(document.addEventListener){
document.addEventListener("mousemove",moveHandler,true);
document.addEventListener("mouseup",upHandler,true);
}
//必须阻止事件传播
if(e.stopPropagation){
e.stopPropagation();
}
//阻止任何默认事件
if(e.preventDefault){
event.preventDefault();
}

}

</script>




<div id="container" style="position:absolute;left:100px;top:100px;width:100px;border:3px solid black;">
<button id="btn" onmousedown="drag(this.parentNode,event)">拖动</button>
</div>