面向对象实现拖拽
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<style type="text/css">
#box{position:absolute; left:100px; top:100px; padding:5px; background:#f0f3f9; font-size:12px; -moz-box-shadow:2px 2px 4px #666666; -webkit-box-shadow:2px 2px 4px #666666;}
#main{border:1px solid #dae5be; background:white;}
#bar{line-height:24px; background: #99c1f9; border-bottom:1px solid #dae5be; padding-left:5px; cursor:move;}
#content{width:420px; height:250px; padding:10px 5px;}
</style>
</head>
<body>
<div id="box">
<div id="main">
<div id="bar">点蓝色部分拖拽</div>
<div id="content">
以下是内容部分。。。。。
</div>
</div>
</div>
<script type="text/javascript">
var oBox = document.getElementById("box");
var oBar = document.getElementById("bar");
startDrag(oBar, oBox);
// 元素的拖拽简单实现
var params = {
left: 0,
top: 0,
currentX: 0,
currentY: 0,
flag: false
};
//获取相关CSS属性
var getCss = function(o,key){
return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,null)[key];
};
//拖拽的实现
var startDrag = function(bar, target){
if(getCss(target, "left") !== "auto"){
params.left = getCss(target, "left");
}
if(getCss(target, "top") !== "auto"){
params.top = getCss(target, "top");
}
//o是移动对象
bar.onmousedown = function(event){
params.flag = true;
if(!event){
event = window.event;
bar.onselectstart = function(){
return false;
}
}
var e = event;
params.currentX = e.clientX;
params.currentY = e.clientY;
};
document.onmouseup = function(){
params.flag = false;
if(getCss(target, "left") !== "auto"){
params.left = getCss(target, "left");
}
if(getCss(target, "top") !== "auto"){
params.top = getCss(target, "top");
}
};
document.onmousemove = function(event){
var e = event ? event: window.event;
if(params.flag){
var nowX = e.clientX, nowY = e.clientY;
var disX = nowX - params.currentX, disY = nowY - params.currentY;
target.style.left = parseInt(params.left) + disX + "px";
target.style.top = parseInt(params.top) + disY + "px";
}
}
};
</script>
</body>
</html>