SVG: Getting the position of an element relative to the page

前端 未结 3 1181
借酒劲吻你
借酒劲吻你 2021-02-02 00:13

I want to display an overlay (html div) when a user clicks on an element in an SVG diagram. To visualize the problem I\'m having, suppose that the SVG image has a horizontal row

相关标签:
3条回答
  • 2021-02-02 00:27

    jQuery's position() does not work well for SVG elements. There is a ticket for that.

    You can use the native SVG method getBBox() to get the position of a SVG element.

    Example

    $('svg circle')[0].getBBox();
    
    0 讨论(0)
  • 2021-02-02 00:29

    In case you haven't worked something out since March (and for anyone else having this problem), try getBoundingClientRect() on your SVG node.

    Returns a ClientRect object that gives you top, bottom, left, right, width, and height relative to the document. Was able to use this to position Twitter Bootstrap popovers (divs) next to SVG rects.

    0 讨论(0)
  • 2021-02-02 00:36

    You can get the position coordinate relative to the page of any element, also <svg>, with this little function:

    function getOffset(element)
    {
        var bound = element.getBoundingClientRect();
        var html = document.documentElement;
    
        return {
            top: bound.top + window.pageYOffset - html.clientTop,
            left: bound.left + window.pageXOffset - html.clientLeft
        };
    }
    

    var offset = getOffset(svg);
    var x = offset.left;
    var y = offset.top;

    live demo: https://codepen.io/martinwantke/pen/rpNLWr

    0 讨论(0)
提交回复
热议问题