简体   繁体   中英

How to drag an image using pageX and PageY of Jquery?

Hello folks I'm novice to Javascript and Jquery. First of all i have an image with id given to it ie #imag_4 and i have kept this on click function inside the function imageDrag().When i do click on the image, i pass the image to the dragMe() function and there i apply pageX and pageY . I am getting the value of pagex and pagey but the image is not moving as the mouse moves... Below is the code

function imageDrag(){
   var imageDragged = null;

   $('.flexslider .slides #listid_4 #imag_4').on('click', function (e) {
      event.stopPropagation();
      if (imageDragged === null) {
         imageDragged = $(this);
            console.log(imageDragged);
         drag(imageDragged);
      }
   });
}

I know there we have Jquery UI 's draggable function, i do not want to use that method. Below is my dragMe function..

function dragMe(imageDragged) {
   $(this).on('mousemove', function (e) {  
      imageDragged.css({
         left: e.pageX,
         top: e.pageY
      });
   });
}

Firstly, you're invoking drag function, whereas you defined dragMe function.

Secondly, jquery click is invoked when you literally click with mouse button ie mouse press and then mouse release. You should use 'mousedown' event to catch this drag-start event.

The last thing is: you should handle mouserelease event to stop dragging the element.

Here is modified & simplified to span element example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM