获取地图区域的位置(html)?

swi*_*itz 3 html javascript maps jquery

这可能吗?我正在尝试找到与浏览器相关的元素的x和y坐标.

var position = $(this).position();
    x = position.left;
    y = position.right;
Run Code Online (Sandbox Code Playgroud)

不行.

有没有办法做到这一点?

http://adamsaewitz.com/housing/
突出显示蓝色房间070

Gab*_*oli 7

问题在于您正在访问区域元素的顶部/左侧.

区域元素不位于其坐标所说的位置.这是由dom/browser在幕后处理的.

因此,您需要找到area与之相关的图像并获取其偏移量.

var imgId = $(this).closest('map').attr('name');
var imgPos = $('#' + imgId).offset();
Run Code Online (Sandbox Code Playgroud)

然后,你抓住它的coords属性area并将其拆分为get left/ top/ width并使用它们来精确定位图像内的位置.

var coords = $(this).attr('coords').split(',');
var box = {
            left: parseInt(coords[0],10),
            top: parseInt(coords[1],10),
            width:  parseInt(coords[2],10)-parseInt(coords[0],10),
            height:  parseInt(coords[3],10)-parseInt(coords[1],10)
            };
Run Code Online (Sandbox Code Playgroud)

考虑到出现的信息框的宽度/高度(并且因为你为它设置动画,也要考虑到这一点)然后你就可以了

x = imgPos.left + box.left + box.width/2 - 65; // 65 is the info width/2
y = imgPos.top + box.top -20 -160 -1; // 20 is the animation, 160 is the info height, 1 is a safe distance from the top
Run Code Online (Sandbox Code Playgroud)

演示:http://www.jsfiddle.net/XBjwN/


Nic*_*ver 6

编辑更新的问题:由于您使用<area>的是不同的故事,因此从coords属性中获取要容易得多,如下所示:

var position = $(this).attr('coords').split(',');
x = +position[0] - 50;
y = +position[1] - 170;
Run Code Online (Sandbox Code Playgroud)

偏移量仅用于说明工具提示本身的硬编​​码宽度/高度。除上述内容外,您还想使用topleft而不是margin-topmargin-left。另外,还要考虑#content <div>页面中的位置,请为它提供一个relative位置,以便工具提示位于其中,如下所示:

#content { position: relative; }
Run Code Online (Sandbox Code Playgroud)

然后...而不是.after()使用,.append()以便将其添加该父对象中。

您可以在此处测试结果


对于原始问题
对象.position()返回具有topleft属性...但是.offset()无论如何您都想要在这里(它相对于document.position()相对于偏移量parent),所以它看起来应该像这样:

var position = $(this).offset(),
    x = position.left,
    y = position.top; //not right!
Run Code Online (Sandbox Code Playgroud)

或这个:

var position = $(this).offset();
var x = position.left;
var y = position.top;
Run Code Online (Sandbox Code Playgroud)

...但是没有一个var逗号分隔的语句,或者var每行都没有一个,您也在创建(或试图)全局变量,这将在IE中爆炸。