首页 > 代码库 > javascript 拖拽
javascript 拖拽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
*{ margin: 0; padding: 0; }
#div1{ width: 100px; height: 100px; background-color: #669; position: absolute; left: 20px; top: 20px; cursor: move; }
#div2{ width: 100px; height: 100px; background-color: #996; position: absolute; left: 200px; top: 200px; cursor: move; }
</style>
</head>
<body>
<div id="div1">拖动的时候不会选中我</div>
<div id="div2">拖动的时候不会选中我</div>
<script>
var page = {
oEvent: function(ev){
return ev || event;
},
pageX: function(ev){
var e = this.oEvent(ev);
return e.clientX;
},
pageY: function(ev){
var e = this.oEvent(ev);
return e.clientY;
},
disX: function(ev){
var e = this.oEvent(ev);
return e.layerX || e.offsetX;
},
disY: function(ev){
var e = this.oEvent(ev);
return e.layerY || e.offsetY;
}
}
drap("div1", page);
drap("div2", page);
function drap(id,option){
var $$ = function(id){
return document.getElementById(id);
}
$$(id).onmousedown = function(ev){
var disX = option.disX();
var disY = option.disY();
document.onmousemove = function(ev){
var left = option.pageX() - disX;
var top = option.pageY() - disY;
$$(id).style.left = left + "px";
$$(id).style.top = top + "px";
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
return false;
}
}
</script>
</body>
</html>
javascript 拖拽