在浏览器滚动中查找元素的位置 [英] Find element's position in browser scroll
问题描述
我需要一些关于寻找元素位置的帮助。
我正在致力于一本电子书阅读器,也是所有带CSS的Html。
所有html分页的页面,我必须找到这样的元素
$ b $ p
< span name =Notestyle例如< / span>
每个人都会建议这样的代码;
函数位置(elem){
var left = 0,
top = 0;
do {
left + = elem.offsetLeft;
top + = elem.offsetTop;
} while(elem = elem.offsetParent);
return [left,top];
} position(document.getElementsByName('Note')[0]);
但它不适用于我;我需要使用JavaScript在scroll中使用元素的真实位置。
var note = document.getElementsByName ( '注释')[0];
var screenPosition = note.getBoundingClientRect();
ClientRect由 getBoundingClientRect()
的值为 .top
, .left
, .right
, .bottom
, .width
和 .height
。
这些是像素在可见窗口上的位置;当你滚动页面时, .top
和 .bottom
值会改变,甚至可能会变成负值,因为项目滚动请注意,不同于积累 offsetLeft
/ 的解决方案, offsetTop
—此解决方案正确计算 body 和
html
元素上的边框和填充在所有浏览器(Firefox)中。
请参阅此测试案例: http://jsfiddle.net/QxYDe/4/ (滚动页面并观察值的变化)。
i need some help about finding elements position. im working on an e-book reader, also its all Html with css. All html sectioned page by page, and i have to find an element like this
<span name="Note" style="background-color:rgb(255,255,204)">Example</span>
Everyone suggests code like this;
function position(elem) {
var left = 0,
top = 0;
do {
left += elem.offsetLeft;
top += elem.offsetTop;
} while ( elem = elem.offsetParent );
return [ left, top ];
}position(document.getElementsByName('Note')[0]);
but it does not work for me; I need element's real position in scroll with JavaScript.
var note = document.getElementsByName('Note')[0];
var screenPosition = note.getBoundingClientRect();
The ClientRect returned by getBoundingClientRect()
has values for .top
, .left
, .right
, .bottom
, .width
, and .height
.
These are pixel positions on the visible window; as you scroll the page the .top
and .bottom
values will change, and may even become negative as the item scrolls off the top of the view.
Note that—unlike the solution accumulating offsetLeft
/offsetTop
—this solution properly accounts for borders and padding on the body
and html
elements in all browsers (Firefox).
See this test case: http://jsfiddle.net/QxYDe/4/ (scroll the page and watch the values change).
Also supported by Internet Explorer.
这篇关于在浏览器滚动中查找元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!