getting mouse position relative to content area of an element

前端 未结 4 1012
臣服心动
臣服心动 2020-12-15 09:25

When the mouse is moved over an element, I want to get the mouse coordinates of the cursor relative to the top-left of the element\'s content area (this is the area excludin

4条回答
  •  北海茫月
    2020-12-15 09:43

    using jQuery:

    function posRelativeToElement(elem, ev){
        var $elem = $(elem),
             ePos = $elem.offset(),
         mousePos = {x: ev.pageX, y: ev.pageY};
    
        mousePos.x -= ePos.left + parseInt($elem.css('paddingLeft')) + parseInt($elem.css('borderLeftWidth'));
        mousePos.y -= ePos.top + parseInt($elem.css('paddingTop')) + parseInt($elem.css('borderTopWidth'));
    
        return mousePos;
    };
    

    live example: http://jsfiddle.net/vGKM3/

    The root of this is simple: compute the element's position relative to the document. I then drop the top & left padding & border (margin is included with basic positioning calculations). The internal jQuery code for doing this is based on getComputedStyle and element.currentStyle. Unfortunately I don't think there is another way...

    The core of jQuery's .offset() function, which gets an element's position relative to document:

    if ( "getBoundingClientRect" in document.documentElement ) {
        ...
        try {
            box = elem.getBoundingClientRect();
        } catch(e) {}
    
        var body = doc.body,
            win = getWindow(doc),
            clientTop  = docElem.clientTop  || body.clientTop  || 0,
            clientLeft = docElem.clientLeft || body.clientLeft || 0,
            scrollTop  = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop ),
            scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
            top  = box.top  + scrollTop  - clientTop,
            left = box.left + scrollLeft - clientLeft;
    
        return { top: top, left: left };
    }else{
        // calculate recursively based on .parentNode and computed styles
    }
    

    Theoretically, another way to do this would be, using the above positioning code:

    • make sure your element has position: relative (or absolute) set
    • append a new element with position: absolute; top:0px; left:0px;
    • get the position of the new element relative to the document. It will be the same as the content position of the parent
    • delete the new element

提交回复
热议问题