js实现div上下左右拉伸
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>div的拉伸</title>
<style type="text/css">
*{padding: 0;margin: 0;}
body{padding: 100px;}
#box{position: absolute;width: 150px;height: 150px;background: orangered;border: 10px solid lightcoral;}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script type="text/javascript">
/*
* 移动得距离就为点击位置坐标(clientX) - 移动后的位置坐标(clientX),那么现在盒子总共的宽度就是其本身宽度(oBox.offsetWidth)加上前面坐标之差。向左拉伸原理差不多,就是多加个改变盒子的位置,盒子的offsetLeft等于光标移动后的位置坐标。我们对盒子就行绝对定位,获取它的left值,将它left值减去改变的距离,他就会向左边拉伸了。上下同理
*/
var oBox = document.getElementById('box');
oBox.onmousedown = function(e){
e = e ||event;
var x = e.clientX;
var y = e.clientY;
var oBoxL = oBox.offsetLeft;
var oBoxT = oBox.offsetTop;
var oBoxW = oBox.offsetWidth;
var oBoxH = oBox.offsetHeight;
var d = 0;
if(x < oBoxL + 10){
d = 'left';
}
else if(x > oBoxL + oBoxW -10){
d = 'right';
}
if(y < oBoxT + 10){
d = 'top';
}
else if(d < oBoxT + oBoxH -10){
d = 'bottom';
}
if(x < oBoxL + 10 && y < oBoxT + 10){
d ='LT';
}
document.onmousemove = function(e){
e = e ||event;
var xx = e.clientX;
var yy = e.clientY;
if(d == 'left'){
oBox.style.width = oBoxW + x -xx + 'px'
oBox.style.left = xx + 'px';
}
else if(d == 'right'){
oBox.style.width = oBoxW + xx -x + 'px'
}
if(d == 'top'){
oBox.style.height = oBoxH + y - yy + 'px';
oBox.style.top = yy + 'px';
}
else if(d == 'bottom'){
oBox.style.height = oBoxH + yy - y + 'px';
}
if(d == 'LT'){
oBox.style.width = oBoxW + x -xx + 'px'
oBox.style.left = xx + 'px';
oBox.style.height = oBoxH + y - yy + 'px';
oBox.style.top = yy + 'px';
}
return false;
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
if(e.preventDefault){
e.preventDefault();
}
}
</script>
</html>
---------------------
作者:sweetllh
来源:CSDN
原文:https://blog.csdn.net/sweetllh/article/details/71367818
版权声明:本文为博主原创文章,转载请附上博文链接!