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>

js 鼠标拖拽改变div宽度高度_第1张图片

你可能感兴趣的:(html,css,js,jq,javascript,css3,css)