jQuery - draggable div with zoom

前端 未结 3 515
暖寄归人
暖寄归人 2020-12-19 00:58

This is my code:

http://jsfiddle.net/652nk/

HTML

3条回答
  •  天命终不由人
    2020-12-19 01:44

    I used both tuze's and Yusuf Demirag's solutions and added a little something for dragging on a grid:

    var gridSize = 20;
    $('#dragme').draggable({
        grid: [ gridSize , gridSize ],
        snap: true,
        snapTolerance: gridSize/2,
    
        drag: function(event,ui){
             var factor = (1 / zoom) -1;
    
             ui.position.top += Math.round((ui.position.top - ui.originalPosition.top) * factor);
             ui.position.top -= ui.position.top % gridSize;
             ui.position.left += Math.round((ui.position.left- ui.originalPosition.left) * factor);
             ui.position.left -= ui.position.left % gridSize;
    
    
             if (ui.position.left < 0) 
                 ui.position.left = 0;
             if (ui.position.left + $(this).width() > canvasWidth)
                 ui.position.left = canvasWidth - $(this).width();  
             if (ui.position.top < 0)
                 ui.position.top = 0;
             if (ui.position.top + $(this).height() > canvasHeight)
                 ui.position.top = canvasHeight - $(this).height();
        }
    });
    

    It has a minor bug (it can't sometimes get to an exact value eg: 160px) but it worked for what I needed.

    Hope it helps.

提交回复
热议问题