jQuery get mouse position within an element

后端 未结 8 805
日久生厌
日久生厌 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:49

    @AbdulRahim answer is almost correct. But I suggest the function below as substitute (for futher reference):

    function getXY(evt, element) {
                    var rect = element.getBoundingClientRect();
                    var scrollTop = document.documentElement.scrollTop?
                                    document.documentElement.scrollTop:document.body.scrollTop;
                    var scrollLeft = document.documentElement.scrollLeft?                   
                                    document.documentElement.scrollLeft:document.body.scrollLeft;
                    var elementLeft = rect.left+scrollLeft;  
                    var elementTop = rect.top+scrollTop;
    
                    x = evt.pageX-elementLeft;
                    y = evt.pageY-elementTop;
    
                    return {x:x, y:y};
                }
    
    
    
    
                $('#main-canvas').mousemove(function(e){
                    var m=getXY(e, this);
                    console.log(m.x, m.y);
                });
    
    0 讨论(0)
  • 2020-11-22 17:54

    To get the position of click relative to current clicked element
    Use this code

    $("#specialElement").click(function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
    }); 
    
    0 讨论(0)
提交回复
热议问题