模拟可移动分隔线:需要禁用默认拖动

Emulating a movable divider: Need to disable default dragging

本文关键字:默认 拖动 可移动 分隔 模拟      更新时间:2023-09-26

我使用html5 + css3 + javascript制作gui应用程序。我试图模仿一个结构,其中一个寡妇被分成两个部分,中间有一个可移动的窗格。当用户拖动窗格时,窗格将跟随鼠标光标,改变两侧两个部分的大小。到目前为止,我得到了以下代码:

<html>
  <head>
    <style>
      .container {
        display : inline-block;
        height : 500px;
      }
      .pane {
        display : inline-block;
        width : 10px;
        height : 100%;
        vertical-align : top;
        color : #806000;
        background-color : #b0d0c0;
      }
      .resbox {
        display : inline-block;
        width : 200px;
        height : 100%;
        background-color : #707070;
      }
    </style>
    <script async="true">
      function dragStart(e, left, right){
        mousedown = true;
        x = e.clientX
        dragOffsetLeft = document.getElementById(left).offsetWidth - x;
        dragOffsetRight = document.getElementById(right).offsetWidth + x;
      };
      function dragRelease(){
        mousedown = false;
      };
      function drag(e, left, right){
        if(!mousedown){return}
        x = e.clientX
        tmpLeft = dragOffsetLeft + x
        tmpRight = dragOffsetRight - x
        if(tmpLeft < 30 || tmpRight < 30){return}
        document.getElementById(left).style.width = tmpLeft + 'px';
        document.getElementById(right).style.width = tmpRight + 'px';
      };
    </script>
  </head>
  <body>
    <span class="container">
      <span id="left" class="resbox">Left</span>
      <span class="pane" onmousedown="dragStart(event, 'left', 'right');" onmousemove="drag(event, 'left', 'right');" onmouseout="dragRelease();" onmouseup="dragRelease();"></span>
      <span id="right" class="resbox">Right</span>
    </span>
  </body>
</html>

它有时有效,但其他时候(特别是在我完成了窗格的拖动之后),中间的窗格会像图片一样拖出位置,并且预期的功能被阻塞。我在<script>...</script>中添加了以下内容,但是没有帮助。

      window.onload = function(){
        document.getElementsByClassName('pane')[0].draggable = false;
      };

我能有关于如何禁用默认拖动的建议吗?我使用firefox 7.0.1和chrome 15.0.874.106。这段代码还有什么其他的改进点可以让动作更加稳定和流畅吗?

首先,在拖动分隔符时停止突出显示文本:

onmousedown="dragStart(event, 'left', 'right'); return false;"
// Returning false stops the default dragging

当光标移动太快时,这仍然不起作用。这是因为分隔符太细,光标可以通过快速移动退出。

我在这里做了一个快速的解决方案:http://jsfiddle.net/np56t/1/

我建议尝试使用jQuery UI Draggable来做正确的