js 鼠标拖拽改变div宽度高度

js 鼠标拖拽改变div宽度高度,

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <style type="text/css">
    body,p{
      margin: 0;
      padding: 0;
    }
    #box {
      position: absolute;
      width: 200px;
      height: 200px;
      background-color: red;
    }
    p {
      font-size: 20px;
      color: white;
    }
  </style>
  <body>
    <div id="box">
      <p></p>
      <p></p>
    </div>
  </body>
  <script>
    var box = document.getElementById("box");
    var p1 = document.getElementsByTagName("p")[0];
    var p2 = document.getElementsByTagName("p")[1];
    box.onmousedown = function (e) {
      var Ev = e;
      var Ex = Ev.clientX; //点击鼠标时储存x轴
      var Ey = Ev.clientY; //点击鼠标时储存y轴
      var dw = box.offsetWidth; //存储默认的div的宽度。
      var dh = box.offsetHeight; //存储默认的div的高度。
      var texb = "";
    
      if (Ev.clientX < box.offsetLeft + box.offsetWidth) {
        //判断鼠标是否在div内
        texb = true;
        console.log(texb);
      }
      document.onmousemove = function (e) {
        if (texb) {
          //判断是在div内移动
          var iE = e;
          if (iE.clientY == 0) {
            //向左移动
            box.style.width = dw + (iE.clientX - Ex) + "px";
          } else if (iE.clientX == 0) {
            //向右移动
            box.style.height = dh + (iE.clientY - Ey) + "px";
          } else if(iE.clientY != 0 && iE.clientX != 0){
            //同时移动
            box.style.width = dw + (iE.clientX - Ex) + "px";
            box.style.height = dh + (iE.clientY - Ey) + "px";
			box.style.background = colorrim()
			
          }else if(box.offsetWidth){
			console.log("sfds")
            //当缩小到一定的范围内不能在缩小
            box.style.width = "20px";
            box.style.height = "20px";
          }
        }
        document.onmouseup = function () {
          //鼠标离开时清除事件
          document.onmousemove = null;
        };
	
          p1.innerText = "宽度:"+box.style.width;
          p2.innerText = "高度:"+box.style.height;
      
      };
    };
    p1.innerText = "宽度:200px";
    p2.innerText = "高度:200px";

	//定义随机颜色
	function colorrim(){
		var a = Math.floor(Math.random() *256);
		 	b = Math.floor(Math.random() *256);
			c = Math.floor(Math.random() *256);
		return "rgb("+ a +","+ b +","+ c +")"
	}
  </script>
</html>

在这里插入图片描述

  • 17
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vue1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值