javascript简单拖拽效果
clientX,Y,鼠标的位置
document.documentElement.clientWidth:获取可视区域的宽度
document.documentElement.clientHeight:获取可视区域的高度
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:100px;
height: 100px;
background-color: red;
position:absolute;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById("div1")
var disX=0;
var disY=0;
//给document添加事件防止拖拽太快跑出div(document无限大)
document.onmousedown=function(ev){
var oEvent=ev||event;
disX=oEvent.clientX-oDiv.offsetLeft;
disY=oEvent.clientY-oDiv.offsetTop;
//clientX,Y,鼠标的位置
document.onmousemove=function(ev){
var oEvent=ev||event;
var l=oEvent.clientX-disX;
var t=oEvent.clientY-disY;
//阻止div跑出页面
if(l<0){l=0;}
if(t<0){t=0;}
if(l>document.documentElement.clientWidth-oDiv.offsetWidth){l=document.documentElement.clientWidth-oDiv.offsetWidth;}
if(t>document.documentElement.clientHeight-oDiv.offsetHeight){t=document.documentElement.clientHeight-oDiv.offsetHeight;}
oDiv.style.left=l+'px';
oDiv.style.top=t+'px';
}
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
//防止火狐的bug
return false;
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>