效果圖如下
1213.gif
原理:
- 同拖拽
- 必須第一步先確定好方向
- 然后在改變
具體見代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽改變DIV的寬度和高度</title>
</head>
<body>
<style>
*{margin:0px;padding:0px;}
#div1{width:400px;height:400px;position:absolute;left:30%;top:25%;background:red;color:yellow;line-height:400px;text-align:center;}
</style>
<div id="div1">
鼠標按住邊緣進行拖拽就有發(fā)現(xiàn)
</div>
<script>
drag(document.getElementById("div1"));
function drag(obj)
{
obj.onmousedown = function(e){
e = e||event;
var dir = ""; //設置好方向
var firstX = e.clientX; //獲取第一次點擊的橫坐標
var firstY = e.clientY; //獲取第一次點擊的縱坐標
var width = obj.offsetWidth; //獲取到元素的寬度
var height = obj.offsetHeight; //獲取到元素的高度
var Left = obj.offsetLeft; //獲取到距離左邊的距離
var Top = obj.offsetTop; //獲取到距離上邊的距離
//下一步判斷方向距離左邊的距離+元素的寬度減去自己設定的寬度,只要點擊的時候大于在這個區(qū)間,他就算右邊
if(firstX>Left+width-30)
{
dir = "right";
}else if(firstX<Left+30)
{
dir = "left";
}
if(firstY>Top+height-30)
{
dir = "down";
}else if(firstY<Top+30)
{
dir = "top";
}
//判斷方向結束
document.onmousemove = function(e){
e = e||event;
switch(dir)
{
case "right":
obj.style["width"] = width+(e.clientX-firstX)+"px";
break;
case "left":
obj.style["width"] = width-(e.clientX-firstX)+"px";
obj.style["left"] = Left+(e.clientX-firstX)+"px";
break;
case "top":
obj.style["height"] = height-(e.clientY-firstY)+"px";
obj.style["top"] = Top+(e.clientY-firstY)+"px";
break;
case "down":
obj.style["height"] = height+(e.clientY-firstY)+"px";
break;
}
}
obj.onmouseup = function(){
document.onmousemove = null;
}
return false;
}
}
</script>
</body>