代码如下:
<!DOCTYPE html>
<html lang="en" onselectstart="return false;">
<head>
<meta charset="UTF-8">
<title>HTML demo之可调整的盒子</title>
<style>
#div{
position: absolute;
box-sizing: border-box;
height: 200px;
width: 200px;
background-color: orange;
top: 200px;
left: 300px;
padding: 10px;
user-select: none;
}
#div div{
position: absolute;
height: 10px;
width: 10px;
background-color: skyblue;
}
#div .T{
width: 100%;
top: 0px;
left: 0px;
cursor: n-resize;
}
#div .B{
width: 100%;
bottom: 0px;
left: 0px;
cursor: s-resize;
}
#div .L{
height: 100%;
left: 0px;
top: 0px;
cursor: w-resize;
}
#div .R{
height: 100%;
right: 0px;
top: 0px;
cursor: e-resize;
}
#div .LT{
left: 0px;
top: 0px;
background-color: green;
cursor: nw-resize;
}
#div .RT{
right: 0px;
top: 0px;
background-color: green;
cursor: ne-resize;
}
#div .LB{
left: 0px;
bottom: 0px;
background-color: green;
cursor: sw-resize;
}
#div .RB{
right: 0px;
bottom: 0px;
background-color: green;
cursor: se-resize;
}
</style>
</head>
<body>
<div id="div"></div>
<script>
var oDiv=document.getElementById("div");
boxResize(oDiv);
function boxResize(obj){
var divArr=[
{
className:"T",
eventFn:[0,1]
},
{
className:"B",
eventFn:[0,-1]
},
{
className:"L",
eventFn:[1,0]
},
{
className:"R",
eventFn:[-1,0]
},
{
className:"LT",
eventFn:[1,1]
},
{
className:"RT",
eventFn:[-1,1]
},
{
className:"LB",
eventFn:[1,-1]
},
{
className:"RB",
eventFn:[-1,-1]
},
];
var oParent=document.createDocumentFragment();
for(var i=0,length=divArr.length;i<length;i++){
var div=document.createElement("div");
div.className=divArr[i].className;
div.index=i;
div.οnmοusedοwn=function(ev){
var ev=ev||window.event;
fn(ev,divArr[this.index].eventFn);
}
oParent.appendChild(div);
}
obj.appendChild(oParent);
document.οnmοuseup=function(){
document.οnmοusemοve=null;
}
function fn(ev,mess){
var ev=ev || window.event;
var pX=ev.clientX;
var pY=ev.clientY;
var cssObj=getComputedStyle(obj)||obj.currentStyle;
var pH=parseFloat(cssObj.height); //原始高度
var pW=parseFloat(cssObj.width); //原始宽度
var pL=obj.offsetLeft; //原始left
var pT=obj.offsetTop; //原始top
document.οnmοusemοve=function(ev){
var ev=ev || window.event;
var Nx=ev.clientX; //鼠标的x
var Ny=ev.clientY; //鼠标的y
var x_=Nx-pX; //纵横坐标的差值
var y_=Ny-pY;
var nW=pW - x_*mess[0];
var nH=pH - y_*mess[1];
var nL=pL + x_*mess[0];
var nT=pT + y_*mess[1];
if(nW<=20){
nW=20;
nL=pL+pW-20;
}
if(nH<=20){
nH=20;
nT=pT+pH-20;
}
obj.style.width=nW+"px";
obj.style.height=nH+"px";
obj.style.left=(mess[0]===1?nL:pL)+"px";
obj.style.top=(mess[1]===1?nT:pT)+"px";
}
}
}
</script>
</body>
</html>
效果如下: