js實現拖拽改變dom元素大小

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
    #panel{
      position: absolute;
      width: 200px;height: 200px;
      background: green;
    }
    #dragIcon{
      position: absolute;bottom: 0;right: 0;
      width: 20px;height: 20px;
      background: yellow;
    }
</style>
</head>
<body>
<div id="panel">
  <div id="dragIcon"></div>
</div>

<script>
  window.onload = function () {
    // 1. 獲取兩個大小div
    var oPanel = document.getElementById('panel');
    var oDragIcon = document.getElementById('dragIcon');
    // 定義4個變量
    var disX = 0;//鼠標按下時光標的X值
    var disY = 0;//鼠標按下時光標的Y值
    var disW = 0; //拖拽前div的寬
    var disH = 0; // 拖拽前div的高
    //3. 給小div加點擊事件
    oDragIcon.onmousedown = function (ev) {
      var ev = ev || window.event;
      disX = ev.clientX; // 獲取鼠標按下時光標x的值
      disY = ev.clientY; // 獲取鼠標按下時光標Y的值
      disW = oPanel.offsetWidth; // 獲取拖拽前div的寬
      disH = oPanel.offsetHeight; // 獲取拖拽前div的高
      document.onmousemove = function (ev) {
        var ev = ev || window.event;
        //拖拽時爲了對寬和高 限制一下範圍,定義兩個變量
        var W = ev.clientX - disX + disW;
        var H = ev.clientY - disY + disH;
        if(W<100){
          W = 100;
        }
        if(W>800){
          W =800;
        }
        if(H<100){
          H = 100;
        }
        if(H>500){
          H = 500;
        }
        oPanel.style.width =W +'px';// 拖拽後物體的寬
        oPanel.style.height = H +'px';// 拖拽後物體的高
      }
      document.onmouseup = function () {
        document.onmousemove = null;
        document.onmouseup = null;
      }
    }
  }
</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章