javascript 拖拽功能
來源:程序員人生 發布時間:2014-12-17 08:28:03 閱讀次數:3633次
拖拽功能是我們常常用到的1個功能,流程以下:
- 鼠標點擊選框時,計算出鼠標位置和選框位置的距離差,也就是disX和disY;
- 鼠標移動,獲得鼠標位置坐標,然后減去步驟1種的距離差,就是選框的坐標;
- 鼠標彈起時,清除鼠標移動函數
需要注意以下幾點:
- 鼠標移動時,有可能移出選框的范圍,所以需要使用全局的移動函數,也就是document.onmousemove;
- 鼠標彈起時,可能不在選框范圍內彈起,程序會出現bug,所以使用全局彈起,也就是 document.onmouseup;
- 要控制選框的移動范圍,使其不能移出閱讀器邊框,通過對上下左右位置的計算,控制選框的坐標始終在閱讀器中。超過坐標臨界值,使變量賦值為臨界值,就能夠實現控制選框移動范圍的功能。
代碼以下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf⑻" />
<title>New Web Project</title>
<style>
#div1{
width:200px;
height:200px;
position:absolute;
background:red;
}
</style>
<script>
window.onload=function(){
var oDiv=document.getElementById('div1');
oDiv.onmousedown=function(evt){
var e=evt||event;
var disX=e.clientX-oDiv.offsetLeft;
var disY=e.clientY-oDiv.offsetTop;
document.onmousemove=function(evt1){
var eMove=evt1||event;
/**
* 控制選框不被拖出閱讀器范圍
*/
var xPos=eMove.clientX-disX;
var yPos=eMove.clientY-disY;
if(xPos<0)
{
xPos=0;
}
else if(xPos>document.documentElement.clientWidth-oDiv.offsetWidth)
{
xPos=document.documentElement.clientWidth-oDiv.offsetWidth;
}
if(yPos<0)
{
yPos=0;
}
else if(yPos>document.documentElement.clientHeight-oDiv.offsetHeight)
{
yPos=document.documentElement.clientHeight-oDiv.offsetHeight;
}
oDiv.style.left=xPos+'px';
oDiv.style.top=yPos+'px';
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
return false;//禁止firefox默許的行動,firefox的1個bug
};
};
</script>
</head>
<body>
<div id='div1'></div>
</body>
</html>
運行結果圖:

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈