查找SVG元素的偏移位置 [英] Finding Offset Position of SVG Element

查看:499
本文介绍了查找SVG元素的偏移位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个问题很多D3。很多时候我喜欢在我的SVG上覆盖HTML对象。

I've run into this problem a lot with D3. A lot of the time I like to overlay HTML objects over my SVG.

我当前的策略是在名为.html-overlay的SVG元素旁边创建一个空DIV。我根据我在主图形(例如:20px)的SVG中设置的内部填充位置。然后我使用以下函数(用jQuery)来确定HTML元素应该在哪里:

My current strategy is creating an empty DIV next to the SVG element called .html-overlay. I position it according to the internal padding I set in the SVG for my main graphic (ex: 20px). Then I use the following function (with jQuery) to figure out where the HTML element should go:

//element is the object returned by D3 .append()
var getOffset: function(element) {
        var $element = $(element[0][0]);
        return {
            left: $element.offset().left - $('.html-overlay').offset().left,
            top: $element.offset().top - $('.html-overlay').offset().top
        };
    }



我想知道,必须有一些内部快速获得元素的偏移量。这是非常有用的(特别是在元素经过多个翻译,旋转,缩放等之后)。

I wonder, there MUST be some internal (non-jQuery dependant) way to quickly get an element's offset. It's very useful (especially after an elements goes through multiple translations, rotations, scales, etc.)

这也将是很好的功能, 中心,元素的最高点,最低点,最左边,最右边等。

It would also be great to have functions for figuring out the offset of the "center" of an element, the topmost point of element, bottommost, leftmost, rightmost, etc.

注意:

由于某种原因,getBoundingClientRect()没有给出正确的数字:

The getBoundingClientRect() doesn't give the correct numbers for some reason:

var $element = $(element[0][0]);

            console.log($element.offset(), element[0][0].getBoundingClientRect())
Object
left: 328
top: 248.8333282470703
__proto__: Object

ClientRect
bottom: 376.83331298828125
height: 139.99998474121094
left: 328
right: 478
top: 236.8333282470703
width: 150


推荐答案

var xywh =element[0][0].getBoundingClientRect();

似乎有一切都在吗?
(原始版本位于此post

seems to have everything in it? (original soution is in this post)

这篇关于查找SVG元素的偏移位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆