如何通过拖动正确调整元素的大小

How to correctly resize an element by dragging?

本文关键字:元素 调整 何通过 拖动      更新时间:2023-09-26

我有两个div作为两个面板,一个在左边,一个在右边。

它们占据了70%和30%的面积。

它们之间有分隔符

当我向左或向右拖动分隔符时,我希望它保持为分隔符的位置。也就是说,我应该能够通过拖动来动态调整左右div的大小。

下面是我的代码:

http://jsbin.com/witicozi/1/edit

HTML:

<!DOCTYPE html>
<html>
<head>
<body>
  <div style='height: 100px'>
    <div id='left'>...</div>
    <div id='separator'></div>
    <div id='right'>...</div>
  </div>
</body>
</html>
CSS:

  #left {
    float: left;
    width: 70%;
    height: 100%;
    overflow: auto;
  }
  #separator {
    float: left;
    width: 3px;
    height: 100%;
    background-color: gray;
    cursor: col-resize;
  }
  #right {
    height: 100%;
    overflow: auto;
  }
JavaScript:

document.querySelector('#separator').addEventListener('drag', function (event) {
  var newX = event.clientX;
  var totalWidth = document.querySelector('#left').offsetWidth;
  document.querySelector('#left').style.width = ((newX / totalWidth) * 100) + '%';
});

问题:

  1. 调整大小发生了,但是分隔符随机地跳跃。它甚至摔倒了很多次。我不知道发生了什么。
  2. 当拖动开始时,鼠标光标变为手。我希望它仍然是col-resize
  3. 很难拖动

请不要使用JQuery

如果您使用console.log(event),则表明event.clientX不完全返回您正在寻找的内容。下面的JavaScript在chrome中为我工作。

document.getElementById('separator').addEventListener('drag', function(event) {
    var left = document.getElementById('left');
    var newX = event.offsetX + left.offsetWidth;
    left.style.width = newX + 'px';
});

它返回的event.offsetX值是左div左上角的位置(px)。这将给您相同的结果,但使用百分比,以便在调整窗口大小时列调整:

document.getElementById('separator').addEventListener('drag', function(event) {
    var left = document.getElementById('left');
    var newX = event.offsetX + left.offsetWidth;
    left.style.width = (newX / window.innerWidth * 100) + '%';
});

采用了一点不同的方法:我没有使用拖放功能,而是使用了一些耦合的鼠标上下监听器。这具有更好的跨浏览器兼容性(至少就我的测试而言),并且它具有能够轻松控制光标的额外好处。

var resize = function(event) {
    var newX = event.clientX;
    document.getElementById('left').style.width = (newX / window.innerWidth * 100) + '%';
};
document.getElementById('separator').addEventListener('mousedown', function(event) {
  document.addEventListener('mousemove', resize);
  document.body.style.cursor = 'col-resize';
});
document.addEventListener('mouseup', function(event) {
  document.removeEventListener('mousemove', resize);
  document.body.style.cursor = '';
});