Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - 获取div / span标记的位置(Get the position of a div/span tag)

Can someone show me how to get the top & left position of a div or span element when one is not specified?(有人可以告诉我如何在未指定divspan元素的情况下获取divspan元素的topleft位置?)

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.(返回55px的值。) However, if I try that for span '12a', then nothing gets returned.(但是,如果我尝试span '12a',则不会返回任何内容。) I have a bunch of div / span s on a page that I cannot specify the top / left properties for, but I need to display a div directly under that element.(我在页面上有一堆div / span s,我无法指定top / left属性,但我需要在该元素下直接显示div 。)   ask by schmoopy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can call the method getBoundingClientRect() on a reference to the element.(您可以在对元素的引用上调用方法getBoundingClientRect() 。)

Then you can examine the top , left , right and/or bottom properties...(然后你可以检查topleftright和/或bottom属性......) var offsets = document.getElementById('11a').getBoundingClientRect(); var top = offsets.top; var left = offsets.left; If using jQuery, you can use the more succinct code...(如果使用jQuery,你可以使用更简洁的代码......) var offsets = $('#11a').offset(); var top = offsets.top; var left = offsets.left;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...