Javascript 检索HTML元素相对于浏览器窗口的位置(X,Y)
我想知道如何获取JavaScript中HTML元素的X和Y位置,例如相对于浏览器窗口的Javascript 检索HTML元素相对于浏览器窗口的位置(X,Y),javascript,html,css,dom,position,Javascript,Html,Css,Dom,Position,我想知道如何获取JavaScript中HTML元素的X和Y位置,例如相对于浏览器窗口的img和div。大多数浏览器上的HTML元素都有:- offsetLeft offsetTop 这些指定元素相对于其最近的父元素(具有布局)的位置。通常可以通过offsetParent属性访问此父级 IE和FF3 clientLeft clientTop 这些属性不太常见,它们指定元素与其父客户端区域的位置(填充区域是客户端区域的一部分,但边框和边距不是)。使用JavaScript框架可能会更好,该框架具有
img
和div
。大多数浏览器上的HTML元素都有:-
offsetLeft
offsetTop
这些指定元素相对于其最近的父元素(具有布局)的位置。通常可以通过offsetParent属性访问此父级
IE和FF3
clientLeft
clientTop
这些属性不太常见,它们指定元素与其父客户端区域的位置(填充区域是客户端区域的一部分,但边框和边距不是)。使用JavaScript框架可能会更好,该框架具有以浏览器独立方式返回此类信息的函数(以及更多!)。以下是一些:
$('id-of-img')。顶部
获取图像的y像素坐标。库经过一定的长度以获得元素的精确偏移。
这里有一个简单的函数,可以在我尝试过的每种情况下完成这项工作
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left;
如果使用jQuery,则非常好,允许您精确地指定所需内容
e、 g
相对位置,绝对位置,无填充的绝对位置,有填充
它还在继续,让我们说你可以用它做很多事情
使用jQuery的另一个好处是它的文件大小轻量级且易于使用,没有jQuery之后您就不会返回JavaScript。如果页面包含至少任何“DIV”,meouw提供的函数会将“Y”值抛出当前页面限制之外。为了找到准确的位置,您需要同时处理offsetParent和parentNode 尝试下面给出的代码(已检查FF2):
jQuery将获取第一个元素的当前坐标,或者设置匹配元素集中每个元素相对于文档的坐标。这是我创建的最好的代码(与jQuery的offset()不同,它也适用于iFrame)。似乎webkit有一点不同的行为 根据meouw的评论:
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
// chrome/safari
if ($.browser.webkit) {
el = el.parentNode;
} else {
// firefox/IE
el = el.offsetParent;
}
}
return { top: _y, left: _x };
}
您可以将两个属性添加到
Element.prototype
中,以获取任何元素的顶部/左侧
Object.defineProperty(Element.prototype,'documentOffsetop'{
get:function(){
返回this.offsetTop+(this.offsetParent?this.offsetParent.documentOffsetTop:0);
}
} );
Object.defineProperty(Element.prototype,'documentOffsetLeft'{
get:function(){
返回this.offsetLeft+(this.offsetParent?this.offsetParent.documentOffsetLeft:0);
}
} );
这叫做:
var x=document.getElementById('myDiv').documentOffsetLeft;
下面是一个将结果与jQuery的
offset()进行比较的演示。top
和。left
:正确的方法是使用:
Internet Explorer一直支持这一点,只要您可能关心它,它最终在年实现了标准化。 所有其他浏览器都采用了它
一些浏览器还返回高度和宽度属性,尽管这是非标准的。如果您担心较旧的浏览器兼容性,请检查此答案的修订版,以获得优化的实现
element.getBoundingClientRect()返回的值与视口相关。如果需要相对于另一个元素的矩形,只需从另一个矩形中减去一个:
var bodyRect = document.body.getBoundingClientRect(),
elemRect = element.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
alert('Element is ' + offset + ' vertical pixels from <body>');
var-bodyRect=document.body.getBoundingClientRect(),
elemRect=element.getBoundingClientRect(),
偏移量=elemRect.top-bodyRect.top;
警报('元素为'+offset+'垂直像素自');
如果您使用jQuery,这可能是一个简单的解决方案:
<script>
var el = $("#element");
var position = el.position();
console.log( "left: " + position.left + ", top: " + position.top );
</script>
var el=$(“#元素”);
变量位置=el.position();
控制台日志(“左:+position.left+”,顶部:+position.top);
在不使用递归函数的情况下高效检索相对于页面的位置:(还包括IE)
我想我也会把这个扔出去
我无法在较旧的浏览器中测试它,但它可以在最新的前3个浏览器中使用。:)
我成功地使用了Andy E的解决方案,根据用户单击的表行中的链接来定位bootstrap 2模式。该页面是Tapestry 5页面,下面的javascript在java页面类中导入
javascript:
function setLinkPosition(clientId){
var bodyRect = document.body.getBoundingClientRect(),
elemRect = clientId.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
offset = offset + 20;
$('#serviceLineModal').css("top", offset);
}
我的模式代码:
<div id="serviceLineModal" class="modal hide fade add-absolute-position" data-backdrop="static"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="top:50%;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<t:zone t:id="modalZone" id="modalZone">
<p>You selected service line number: ${serviceLineNumberSelected}</p>
</t:zone>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<!-- <button class="btn btn-primary">Save changes</button> -->
</div>
希望这对某人有所帮助,这篇文章起到了帮助。我发现的最干净的方法是jQuery的offset
使用的技术的简化版本。与其他一些答案类似,它以getBoundingClientRect
开头;然后,它使用窗口
和文档元素
调整滚动位置以及正文
上的边距(通常是默认值)
var els=document.getElementsByTagName(“div”);
var docEl=document.documentElement;
对于(变量i=0;i
div{
宽度:100px;
高度:100px;
背景色:红色;
边框:1px纯黑;
}
#雷尔{
位置:相对位置;
左:10px;
顶部:10px;
}
#腹肌{
位置:绝对位置;
顶部:250px;
左:250px;
}
因为不同的浏览器以不同的方式呈现边框、填充、边距等。我编写了一个小函数来检索特定元素在每个根元素中的顶部和左侧位置,您需要精确的维度:
function getTop(root, offset) {
var rootRect = root.getBoundingClientRect();
var offsetRect = offset.getBoundingClientRect();
return offsetRect.top - rootRect.top;
}
对于检索左位置,必须返回:
return offsetRect.left - rootRect.left;
此函数用于返回元素相对于整个文档(页面)的位置:
利用这个我们可以
function setLinkPosition(clientId){
var bodyRect = document.body.getBoundingClientRect(),
elemRect = clientId.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
offset = offset + 20;
$('#serviceLineModal').css("top", offset);
<div id="serviceLineModal" class="modal hide fade add-absolute-position" data-backdrop="static"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="top:50%;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<t:zone t:id="modalZone" id="modalZone">
<p>You selected service line number: ${serviceLineNumberSelected}</p>
</t:zone>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<!-- <button class="btn btn-primary">Save changes</button> -->
</div>
<t:loop source="servicesToDisplay" value="service" encoder="encoder">
<tr style="border-right: 1px solid black;">
<td style="white-space:nowrap;" class="add-padding-left-and-right no-border">
<a t:type="eventLink" t:event="serviceLineNumberSelected" t:context="service.serviceLineNumber"
t:zone="pageZone" t:clientId="modalLink${service.serviceLineNumber}"
onmouseover="setLinkPosition(this);">
<i class="icon-chevron-down"></i> <!-- ${service.serviceLineNumber} -->
</a>
</td>
void onServiceLineNumberSelected(String number){
checkForNullSession();
serviceLineNumberSelected = number;
addOpenServiceLineDialogCommand();
ajaxResponseRenderer.addRender(modalZone);
}
protected void addOpenServiceLineDialogCommand() {
ajaxResponseRenderer.addCallback(new JavaScriptCallback() {
@Override
public void run(JavaScriptSupport javascriptSupport) {
javascriptSupport.addScript("$('#serviceLineModal').modal('show');");
}
});
}
var rect = el.getBoundingClientRect();
var docEl = document.documentElement;
var rectTop = rect.top + window.pageYOffset - docEl.clientTop;
var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;
function getTop(root, offset) {
var rootRect = root.getBoundingClientRect();
var offsetRect = offset.getBoundingClientRect();
return offsetRect.top - rootRect.top;
}
return offsetRect.left - rootRect.left;
function getOffset(el) {
const rect = el.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
getOffset(element).left
getOffset(element).top
export type ElementOffset = {
left: number;
top: number
};
/**
* Returns an element's position relative to the whole document (page).
*
* If the element does not exist, returns O/O (top-left window corner).
*
* @example getOffset(document.getElementById('#element'));
*
* @param el
* @see https://stackoverflow.com/a/28222246/2391795
*/
export const getElementOffset = (el: Element | null): ElementOffset => {
const rect = el?.getBoundingClientRect();
return {
left: (rect?.left || 0) + window?.scrollX,
top: (rect?.top || 0) + window?.scrollY,
};
};
export default getElementOffset;
// For really old browser's or incompatible ones
function getOffsetSum(elem) {
var top = 0,
left = 0,
bottom = 0,
right = 0
var width = elem.offsetWidth;
var height = elem.offsetHeight;
while (elem) {
top += elem.offsetTop;
left += elem.offsetLeft;
elem = elem.offsetParent;
}
right = left + width;
bottom = top + height;
return {
top: top,
left: left,
bottom: bottom,
right: right,
}
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop;
var clientLeft = docElem.clientLeft;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
var bottom = top + (box.bottom - box.top);
var right = left + (box.right - box.left);
return {
top: Math.round(top),
left: Math.round(left),
bottom: Math.round(bottom),
right: Math.round(right),
}
}
function getOffset(elem) {
if (elem) {
if (elem.getBoundingClientRect) {
return getOffsetRect(elem);
} else { // old browser
return getOffsetSum(elem);
}
} else
return null;
}
function getPosition(e) {
var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1);
var x = 0, y = 0;
while (e) {
x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0);
y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0);
e = e.offsetParent;
}
return { x: x + window.scrollX, y: y + window.scrollY };
}
getAbsoluteOffsetFromBody = function( el )
{ // finds the offset of el from the body or html element
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
getAbsoluteOffsetFromGivenElement = function( el, relativeEl )
{ // finds the offset of el from relativeEl
var _x = 0;
var _y = 0;
while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
getAbsoluteOffsetFromRelative = function( el )
{ // finds the offset of el from the first parent with position: relative
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft + el.clientLeft;
_y += el.offsetTop - el.scrollTop + el.clientTop;
el = el.offsetParent;
if (el != null)
{
if (getComputedStyle !== 'undefined')
valString = getComputedStyle(el, null).getPropertyValue('position');
else
valString = el.currentStyle['position'];
if (valString === "relative")
el = null;
}
}
return { top: _y, left: _x };
}
function getPosition( el ) {
var x = 0;
var y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
x += el.offsetLeft - el.scrollLeft;
y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: y, left: x };
}
function findLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.left + window.scrollX;
} //call it like findLeft('#header');
function findTop(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.top + window.scrollY;
} //call it like findTop('#header');
function findTopLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return {top: rec.top + window.scrollY, left: rec.left + window.scrollX};
} //call it like findTopLeft('#header');
window.visualViewport.pageTop
let bodyElement = document.getElementsByTagName('body')[0];
let elementToTrack = bodyElement.querySelector('.trackme');
trackedObjPos = elementToTrack.getBoundingClientRect().top;
if(trackedObjPos > 264)
{
bodyElement.style.cssText = '';
}
var elm = $('#div_id'); //get the div
var posY_top = elm.offset().top; //get the position from top
var posX_left = elm.offset().left; //get the position from left
window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y
window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X
function getParentOffsets(el): number {
if (el.offsetParent) {
return el.offsetParent.offsetTop + getParentOffset(el.offsetParent);
} else {
return 0;
}
}
el.offsetTop + getParentOffsets(el);
/**
*
* @param {HTMLElement} el
* @return {{top: number, left: number}}
*/
function getDocumentOffsetPosition(el) {
var position = {
top: el.offsetTop,
left: el.offsetLeft
};
if (el.offsetParent) {
var parentPosition = getDocumentOffsetPosition(el.offsetParent);
position.top += parentPosition.top;
position.left += parentPosition.left;
}
return position;
}
var elem = document.getElementById("id");
alert(elem.getBoundingClientRect());