JavaScript & jQuery; how to do snapping drag and drop

前端 未结 1 761
猫巷女王i
猫巷女王i 2021-02-08 19:54

I am looking for advice from all you wonderful people on the best way to do snapping drag and drop.

As part of a simple board game I am currently coding in JS (using jQu

1条回答
  •  时光说笑
    2021-02-08 20:20

    Hope this will help you, this is for Drag & Drop with snap in jQuery

    var snap = 10; /* the value of the snap in pixels */
    var l,t,xInit,yInit,x,y;
    $(document).mousemove(function(e) {
      x = e.pageX;
      y = e.pageY;
      drag(snap);
    });
    
    $('#obj').mousedown(function(e){
      l=$('#obj').position().left;
      t=$('#obj').position().top;
      xInit = e.pageX;
      yInit = e.pageY;
    })
    
    
    function drag(snap){
        w=$('#obj').width();
        h=$('#obj').height();
        var left = l+x-xInit;
        var top = t+y-yInit;
      if(!snap==0){
        left = (left/snap).toFixed()*snap;
        top = (top/snap).toFixed()*snap;
        $('#obj').css('left',left);
        $('#obj').css('top',top);
      }else{
        $('#obj').css('left',left);
        $('#obj').css('top',top);
      }
    }
    

    0 讨论(0)
提交回复
热议问题