获取div / span标签的位置 [英] Get the position of a div/span tag

查看:150
本文介绍了获取div / span标签的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我如何获得顶部& left 在 div span 没有指定?





 < span id =' 11a'style ='top:55px;'onmouseover =GetPos(this);> stuff< / span> 
< span id ='12a'onmouseover =GetPos(this);> stuff< / span>

在上面,如果我这样做的话:

< pre $ document.getElementById('11a')。style.top

返回 55px 的值。但是,如果我尝试 span '12a',则不会返回任何内容。



我有一堆 div / span s在我无法指定顶部 / 左侧属性的页面上,但我需要显示 div 直接在该元素下。

解决方案

这个函数会告诉你x,y的位置相对于页面的元素。基本上,你必须循环所有元素的父母,并将他们的偏移量加在一起。

  function getPos(el){
// yay可读性
for(var lx = 0,ly = 0;
el!= null;
lx + = el.offsetLeft,ly + = el.offsetTop,el = el .offsetParent);
return {x:lx,y:ly};
}

但是,如果您只是想要元素的x,y位置相对于它的容器,然后你需要的是:

  var x = el.offsetLeft,y = el.offsetTop; 

要将一个元素直接放在这个元素下面,您还需要知道它的高度。这存储在offsetHeight / offsetWidth属性中。

  var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin; 


Can someone show me how to get the top & left position of a div or span element when one is not specified?

ie:

<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>

In the above, if I do:

document.getElementById('11a').style.top

The the value of 55px is returned. However, if I try that for span '12a', then nothing gets returned.

I have a bunch of div/spans on a page that I cannot specify the top/left properties for, but I need to display a div directly under that element.

解决方案

This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.

function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}

However, if you just wanted the x,y position of the element relative to its container, then all you need is:

var x = el.offsetLeft, y = el.offsetTop;

To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.

var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;

这篇关于获取div / span标签的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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