AngularJS - Snapping drag
-
20-12-2019 - |
Вопрос
Looking at the guide from AngularJS website (http://docs.angularjs.org/guide/compiler), I have:
app.directive('task', function($document){
return {
restrict: 'C',
link: function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.screenX - x;
startY = event.screenY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.screenY - startY;
x = event.screenX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
}
});
This works fine, except I don't want the smooth dragging feature. Rather, I want to drag the item for say 200px, and then I want it to snap to that position, and then if moved another 200, then snaps back again. How can I do that?
Решение
If you have a fixed grid, just apply that to your X and Y coordinates like so:
y = event.screenY - startY;
x = event.screenX - startX;
y = y - ( y % gridSizeY );
x = x - ( x % gridSizeX );
Не связан с StackOverflow