jQuery get mouse position within an element

后端 未结 8 944
日久生厌
日久生厌 2020-11-22 16:56

I was hoping to craft a control where a user could click inside a div, then drag the mouse, then let up on the mouse in order to indicate how long they want something to be.

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 17:36

    One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

    $("#something").click(function(e){
       var parentOffset = $(this).parent().offset(); 
       //or $(this).offset(); if you really just want the current element's offset
       var relX = e.pageX - parentOffset.left;
       var relY = e.pageY - parentOffset.top;
    });
    

提交回复
热议问题