-2

我正在尝试为垂直调整大小的div.

这是我走了多远,但我不确定这是否是最佳实践。

编辑

我想让这段代码可重用,正如你在我的例子中看到的那样,如果我有超过 2,3 个不同的 re-sizers,这是相当困难的。


提琴手

JS

var moveHandler = function (e) {
    var leftPos = e.pageX - $("#container").position().left;
    var rightPos = $("#container").width() - e.pageX + 40;
    $("#separator").css("left", leftPos + "px");
    $("#left-side").css("right", rightPos + "px");
    $("#right-side").css("left", leftPos + "px");
}

$("#separator").on('mousedown', function () {
    $("#container").on('mousemove.resize', moveHandler);
    $("#separator").css("background-color", "gray");
});
$(window).on('mouseup', function () {
    $("#separator").css("background-color", "");
    $("#container").off('mousemove.resize')
});

HTML

<div id="container">
    <div id="left-side">.</div>
    <div id="separator"></div>
    <div id="right-side">.</div>
</div>
4

1 回答 1

2

以下是处理任意数量的适当配置的滑块元素的纯 JavaScript:

(function () {
  function mouseDown (ev) {
    function mouseMove (ev) {
      originX = parseInt (window.getComputedStyle (slider).left, 10) + 
                  ev.screenX - originX;
      if (originX >= 5 && originX <= cWidth - 10)
        slider.style.left = slider.previousElementSibling.style.width = 
            slider.nextElementSibling.style.left = originX + 'px';  
      originX = ev.screenX;
    }

    function mouseUp (ev) {
      document.removeEventListener ('mousemove', mouseMove, false)
      document.removeEventListener ('mouseup', mouseUp, false)
      slider.classList.remove ('active');
    }

    var slider = this,
        originX = ev.screenX,
        cWidth = parseInt (window.getComputedStyle (slider.parentNode).width, 10);
    slider.classList.add ('active');
    document.addEventListener ('mousemove', mouseMove, false)
    document.addEventListener ('mouseup', mouseUp, false)
  }

  [].forEach.call (document.querySelectorAll ('.slider'), function (slider) {
      var left = slider.previousElementSibling,
          right = slider.nextElementSibling;

      slider.parentNode.classList.add ('container');

      slider.classList.remove ('active');
      slider.addEventListener ('mousedown', mouseDown, false);

      left.style.position = right.style.position = 'absolute';
      left.style.width = right.style.left = window.getComputedStyle (slider).left;
      left.style.left = right.style.right = '0px';
    });
}) ();

配置如下:

 <div>  <!- container -->
    <div></div>  <!- left side -->
    <div class="slider"></div>  <!- slider -->
    <div></div>  <!- right side -->
 </div>

需要以下CSS:

.container { position: relative; }

.slider {
    position: absolute;
    z-index: 2;
    width: 5px;
    cursor: col-resize;
    top: 0;
    bottom: 0;    
}

代码通过查找类名触发,slider然后修复大部分样式值。

有关更多详细信息,请参见小提琴:http: //jsfiddle.net/jstoolsmith/VCdE5/

于 2013-07-07T10:03:31.703 回答