只記錄left谦纱,top同理沉颂。
clientX:返回鼠標(biāo)相對(duì)于瀏覽器的水平坐標(biāo)个初;
offsetLeft:返回當(dāng)前對(duì)象距離瀏覽器(父對(duì)象)的左側(cè)距離沈堡;
offsetWidth:對(duì)象的可見(jiàn)寬度;
onmousemove:鼠標(biāo)移動(dòng)事件浪听;
連接點(diǎn)是鼠標(biāo)放在div上拖動(dòng)時(shí)的位置(坐標(biāo))不會(huì)改變的螟碎,起名字為unchangX;
鼠標(biāo)拖動(dòng)事件是利用position:absolute絕對(duì)定位改變left和top迹栓,left的位置是通過(guò)clientX-unchangeX得到的掉分。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>鼠標(biāo)拖拽事件</title>
<style type="text/css">
#box{
width:100px;
height:100px;
background-color:cornflowerblue;
position:absolute;
left:0;
top:0;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
window.onload = function(){
var oDiv = document.getElementById("box"),
unchangeX = 0,
unchangeY = 0;
oDiv.onmousedown =function(ev){//鼠標(biāo)按下
var oEvent=ev||event;
var unchangeX = oEvent.clientX - oDiv.offsetLeft;//鼠標(biāo)的x坐標(biāo)減去box的左邊距離,unchangeX這個(gè)距離是不會(huì)變的,通過(guò)這個(gè)新鼠標(biāo)的X坐標(biāo)減去unchangeX就是box的Left
var unchangeY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove = function(ev){//為了防止鼠標(biāo)移動(dòng)太快而離開了DIV產(chǎn)生了bug酥郭,所以要給整個(gè)頁(yè)面加onmousemove事件
var oEvent = ev||event;
var oLeft = oEvent.clientX - unchangeX;
var oTop = oEvent.clientY - unchangeY;
//優(yōu)化部分:鼠標(biāo)移動(dòng)到瀏覽器左側(cè)尔崔、右側(cè)、上側(cè)褥民、下側(cè)時(shí)的問(wèn)題
if(oLeft < 0){
oLeft = 0;
}else if(oLeft>document.documentElement.clientWidth - oDiv.offsetWidth){
oLeft = document.documentElement.clientWidth - oDiv.offsetWidth;
}
if(oTop < 0){
oTop = 0;
}else if(oTop>document.documentElement.clientHeight - oDiv.offsetHeight){
oTop = document.documentElement.clientHeight - oDiv.offsetHeight;
}
oDiv.style.left = oLeft + 'px';
oDiv.style.top = oTop + 'px';
};
document.onmouseup = function(){//鼠標(biāo)松開時(shí)
document.onmousemove = null;//把鼠標(biāo)移動(dòng)清除
document.onmouseup = null;//把鼠標(biāo)松開清除
};
return false;
};
}
</script>
</body>
</html>