代码之家  ›  专栏  ›  技术社区  ›  sanjihan

拖动时实现更改值(就像在Photoshop中一样)

  •  -2
  • sanjihan  · 技术社区  · 9 年前

    http://i.imgur.com/9QeoUNx.png

    这是初学者(几乎为空)模板:

    https://codepen.io/anon/pen/owadRe

    <div class="drag">123</div>
    
    .drag{
      cursor: ew-resize;
    }
    

    1 回复  |  直到 9 年前
        1
  •  1
  •   Khauri    9 年前

    如果你在谷歌上搜索,有一些插件可以做到这一点,但实际上,这只是一个不断获取鼠标相对于单击元素的x位置的问题,然后根据该距离(或该距离的某种转换)更新值。

    下面是一个使用jquery的简单而快速的示例。

    $(".drag").on('mousedown', e => {
      // get initial value
      let val = parseInt($('.drag').text());
      $('body, .drag').toggleClass('dragging');
      // check mousemove
      $('body').on('mousemove', e => {
        let xinit = $('.drag').offset().left; // element x position
        let xfin = e.pageX; // mouse x position
        let dVal = Math.floor(val + (xfin - xinit));
        $('.drag').text(dVal);
      });
      // remove mousemove when done clicking
      $('body').on('mouseup', e => {
        $('body, .drag').toggleClass('dragging');
        $('body').off('mousemove');
      })
    })
    body, html{
      width : 100%;
      height : 100%;
      display : flex;
      align-items : center;
      justify-content : center;
      background-color : yellow;
    }
    body.dragging{
      cursor : ew-resize;
    }
    .drag {
      cursor: ew-resize;
        -webkit-touch-callout: none; /* iOS Safari */
        -webkit-user-select: none; /* Safari */
         -khtml-user-select: none; /* Konqueror HTML */
           -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* Internet Explorer/Edge */
                user-select: none
    }
    <body>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div class="drag">123</div>
    </body>