jQuery get mouse position within an element

后端 未结 8 945
日久生厌
日久生厌 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条回答
  •  旧时难觅i
    2020-11-22 17:36

    This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):

    function getXY(evt) {
        var element = document.getElementById('elementId');  //replace elementId with your element's Id.
        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;
    
            if (document.all){ //detects using IE   
                x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
                y = event.clientY+scrollTop-elementTop;
            }
            else{
                x = evt.pageX-elementLeft;
                y = evt.pageY-elementTop;
        }
    

提交回复
热议问题