Ionic and AngularJS - Drag and drop an element - how to get mouse position?

So, I'm trying to make the HTML element move around the page with my finger (or with the mouse on the desktop). First, the element is hidden, the other three are shown, and when you drag one of them, the hidden element opens and moves with your finger - the original element remains in place. After releasing, the drag element disappears.

So here is what I did:

HTML:

<div on-drag="onDrag($event)" on-release="onRelease($event)" id="dragger_1" class="large greenbg" ng-class="{shadowClass: doshadow==1}">drag 1</div> <div on-drag="onDrag($event)" on-release="onRelease($event)" id="dragger_2" class="large redbg" ng-class="{shadowClass: doshadow==2}">drag 2</div> <div on-drag="onDrag($event)" on-release="onRelease($event)" id="dragger_3" class="large bluebg" ng-class="{shadowClass: doshadow==3}">drag 3</div> <div id="dragged" class="mini" ng-class="{hidden: doshadow == 0}" ng-style="draggedStyle">dragged</div> 

Controller:

 myApp.controller("playerCtrl", ["$stateParams", "$scope", function($stateParams, $scope) { $scope.player = $stateParams.playerId; $scope.doshadow = 0; $scope.draggedStyle = {}; $scope.onDrag = function(event) { //console.log('Reporting : drag'); console.log(event.target.className); $scope.doshadow = event.target.id.substr(8, 1); $scope.draggedStyle = { 'left': '30px', 'top': '50px' }; } $scope.onRelease = function(event) { //console.log(event.target); $scope.doshadow = 0; $scope.draggedStyle = {}; } }]); 

So, this works great ... The only thing I still need to do - and I don’t know how it is - is to fix the position in accordance with the movement, and not correct it to 30px / 50px, as it was at present.

So, two things: -I am doing everything right? - Can you help me deal with this mouse problem?

I start with Angular, and it took me 6 hours to work: D

Thank you very much!

+6
source share
2 answers

Look at the $event object, you will need event.gesture , in which you will find the center field, which is the center of the current position for your gesture.

You may need an absolute dragged value and set the offsets accordingly.

+4
source

If everything works fine, you just need to read the mouse position outside the event data:

 $scope.draggedStyle = { 'left': event.clientX, 'top': event.clientY }; 

You probably also need to add an offset, but this is an idea.

Note. For phones, you need to look up the event.touches array.

Some useful pages:

+1
source

Source: https://habr.com/ru/post/978883/


All Articles