拖动两个文本框并使用JavaScript调整文本框的宽度

问题描述 投票:0回答:1

我有两个连续的文本框。我想拖动并调整文本框的宽度。类似于:“https://www.tutorialspoint.com/online_markdown_editor.php”(仅限拖动系统)。 我已经尝试过,但是拖动不流畅,无法拖动全角。

//index.html

<!DOCTYPE html>
<html>
<head>
  <title>Log Converter</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    #input,
    #output {
      height: 80vh;
    }

    * {
    box-sizing: border-box;
    }
    
    .bar {
        height: 90%;
        width: 2px;
        background-color: #ddd;
        cursor: w-resize;
    }
  </style>
</head>
<body class="bg-gray-100">
  <div class="container mx-auto mt-10 p-4">
    <div class="flex gap-2">
        <div class="w-full left">
          <div class="editor">
            <textarea id="input" class="w-full h-48 p-4 bg-white rounded" placeholder="Enter logs here..."></textarea>
          </div>
          <button class="btn bg-green-500 text-white px-4 py-2 mt-4" onclick="convertLogs()">Convert</button>
        </div>
        <div><div class="bar w-1" title="Click & Drug"></div></div>
        <div class="w-full right">
            <textarea id="output" class="w-full h-48 p-4 bg-white rounded" readonly></textarea>
        </div>
    </div>
  </div>
      
  <script>
    const left = document.querySelector(".left"),
          bar = document.querySelector(".bar");

    const drag = (e) => {
        left.style.width = (e.pageX + (bar.offsetWidth * 148)) + "px";
    }

    bar.addEventListener("mousedown", () => {
        document.addEventListener("mousemove", drag);
    })

    window.addEventListener("click", () => {
        document.removeEventListener("mousemove", drag);
    })
  </script>
</body>
</html>

我不擅长前端设计,请有人帮助我。预先感谢。

javascript html jquery css drag
1个回答
0
投票

终于找到解决方案了。

更新 HTML

<textarea id="input" class="w-full h-48 p-4 bg-white rounded leftbox" 
placeholder="Enter logs here..."></textarea>
<textarea id="output" class="w-full h-48 p-4 bg-white rounded rightbox" 
readonly></textarea>

刚刚添加了“leftbox”和“rightbox”类。

添加CSS

#input {
  resize: horizontal;
  min-width: 90px;
  max-width: 1450px;
}
#output {
  resize: none;
}

添加脚本

const left = document.querySelector(".leftbox"),
      right = document.querySelector(".rightbox");

left.addEventListener("mousedown", () => {
    document.addEventListener("mousemove", function(){
      if (left.offsetWidth < 748) {
        right.style.width = (748 + (748 - left.offsetWidth)) + "px";
        
      } else {
        right.style.width = (748 - (left.offsetWidth - 748)) + "px";
      }
    });
})
© www.soinside.com 2019 - 2024. All rights reserved.