SVG:获取元素相对于页面的位置 [英] SVG: Getting the position of an element relative to the page

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

问题描述

当用户点击SVG图中的元素时,我想显示一个overlay(html div)。为了可视化我遇到的问题,假设SVG图像具有6个元素的水平行。在点击事件中,我得到元素的坐标,并使用它们来显示旁边的叠加层。问题是,当我从左到右单击元素时,我注意到元素和覆盖之间的水平偏移量越来越小。也就是说,第六个元素显示与第一个元素更接近的叠加层。这是在Chrome和FF中发生的,这是一个问题,因为覆盖面覆盖了元素本身。

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 of 6 elements. At the click event, I get the element's coordinates and use them to display the overlay next to it. The problem is that as I click the elements from left to right, I notice that the horizontal offset between the element and the overlay keeps getting smaller. That is, the 6th element displays the overlay much closer to it than the first element. This happens in both Chrome and FF, and it's an issue because sometime the overlay covers the element itself.

起初我正在使用JQuery的position()属性, t表现出我上面描述的行为,但它在Chrome和Firefox中返回了非常不同的值,此外它还没有正式支持JQuery on svg元素。所以我尝试使用DOM的标准offsetLeft和offsetTop,以及svg的x.animVal.value属性和我在Web上找到的各种库,但它们都具有相同的不正确的偏移问题。我认为这是因为svg图像被缩放,所以我正在寻找我的方式来获取一个svg的元素位置相对于包含它的实际html文档。有没有办法这样做?

At first I was using JQuery's position() property, which didn't exhibit the behavior that I described above, but it returned very different values in Chrome and Firefox, plus it is not officially supported by JQuery on svg elements. So I tried with DOM's standard offsetLeft and offsetTop, as well as svg's x.animVal.value property and various libraries that I found on the web, but they all have the same erratic offset problem. I presume that this happens because the svg image is scaled, so I'm looking for I way to just get an svg's element position relative to the actual html document which contains it. Is there a way to do this?

推荐答案

如果你从三月份以来没有工作过这个问题),在您的SVG节点上尝试 getBoundingClientRect()

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

返回一个 ClientRect 对象,它给出了相对于文档的顶部,底部,左侧,右侧,宽度和高度。可以使用它将Twitter Bootstrap popovers(divs)定位在SVG rects旁边。

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.

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

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