js改变div大小

本文介绍了一种通过拖动方式来调整HTML页面中DIV元素尺寸的方法。利用JavaScript实现了鼠标按下时捕捉位置,并根据鼠标移动方向调整DIV的宽度、高度及位置。此功能适用于需要用户交互调整元素大小的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<style>
#div1{
width: 100px;
height: 100px;
position: absolute;
top: 100px;
left: 300px;
background-color: rgba(0,0,0,0.2);
}
</style>
<div id="div1">adfadsf</div>
<script type="text/javascript">
function chanDivSize(obj){
var oDiv = document.getElementById(obj);
oDiv.onmousedown = function(ev){
// 获取event对象,兼容性写法
var ev = ev || event;
// 鼠标按下时的位置
var mouseDownX = ev.clientX;
var mouseDownY = ev.clientY;
// 方块上下左右四个边的位置和方块的长宽
var T0 = this.offsetTop;
var B0 = this.offsetTop + this.offsetHeight;
var L0 = this.offsetLeft;
var R0 = this.offsetLeft + this.offsetWidth;
var W = this.offsetWidth;
var H = this.offsetHeight;
// 设置方块的识别范围
var areaT = T0 + 10;
var areaB = B0 - 10;
var areaL = L0 + 10;
var areaR = R0 - 10;
// 判断改变方块的大小的方向
// 左
var changeL = mouseDownX < areaL;
// 右
var changeR = mouseDownX > areaR;
// 上
var changeT = mouseDownY < areaT;
// 下
var changeB = mouseDownY > areaB;
// IE8 取消默认行为-设置全局捕获
if(oDiv.setCapture){
oDiv.setCapture();
}
document.onmousemove = function(ev){
var ev = ev || event;
// 鼠标移动时的鼠标位置
var mouseMoveX = ev.clientX;
var mouseMoveY = ev.clientY;
//根据改变方块大小的方向不同进行大小的改变
// 左
if(changeL){
oDiv.style.width = (mouseDownX - mouseMoveX) + W + 'px';
oDiv.style.left = L0 - (mouseDownX - mouseMoveX) + 'px';
}
// 右
if(changeR){
oDiv.style.width = (mouseMoveX - mouseDownX) + W + 'px';
}
// 上
if(changeT){
oDiv.style.height = (mouseDownY - mouseMoveY) + H + 'px';
oDiv.style.top = T0 - (mouseDownY - mouseMoveY) + 'px';
}
// 下
if(changeB){
oDiv.style.height = (mouseMoveY - mouseDownY) + H +'px';
}
// 限定范围
if(parseInt(oDiv.style.width) < 50){
oDiv.style.width = 50 + 'px';
}
if(parseInt(oDiv.style.height) < 50){
oDiv.style.height = 50 + 'px';
}
}
document.onmouseup = function(){
document.onmousemove = null;
// 释放全局捕获
if(oDiv.releaseCapture){
oDiv.releaseCapture();
}
}
return false;
}
}
chanDivSize("div1");
</script>
</body>
</html>

转载于:https://www.cnblogs.com/zyx-blog/p/9335387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值