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

前端 未结 3 1182
借酒劲吻你
借酒劲吻你 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:36

    You can get the position coordinate relative to the page of any element, also , 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

提交回复
热议问题