我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
您可以将两个财产添加到Element.protype中,以获得任何元素的顶部/左侧。
Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );
Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
get: function () {
return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
}
} );
这被称为:
var x = document.getElementById( 'myDiv' ).documentOffsetLeft;
下面是一个将结果与jQuery的offset().top和.left进行比较的演示:http://jsfiddle.net/ThinkingStiff/3G7EZ/
其他回答
如果您使用jQuery,这可能是一个简单的解决方案:
<script>
var el = $("#element");
var position = el.position();
console.log( "left: " + position.left + ", top: " + position.top );
</script>
您可以将两个财产添加到Element.protype中,以获得任何元素的顶部/左侧。
Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );
Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
get: function () {
return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
}
} );
这被称为:
var x = document.getElementById( 'myDiv' ).documentOffsetLeft;
下面是一个将结果与jQuery的offset().top和.left进行比较的演示:http://jsfiddle.net/ThinkingStiff/3G7EZ/
这样怎么样,通过传递元素的ID,它将返回左侧或顶部,我们还可以组合它们:
1) 查找左侧
function findLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.left + window.scrollX;
} //call it like findLeft('#header');
2) 查找顶部
function findTop(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.top + window.scrollY;
} //call it like findTop('#header');
或3)找到左侧和顶部
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');
这是一个使用vanilla JS递归迭代element.offsetTop和element.ooffsetParent的现代1行代码:
功能:
getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent))
用法:
const el = document.querySelector('#div_id');
const elTop = getTop(el)
优势:
无论当前滚动位置如何,始终返回绝对垂直偏移。
传统语法:
function getTop(el) {
return el.offsetTop + (el.offsetParent && getTop(el.offsetParent));
}
大多数浏览器上的HTML元素将具有:-
offsetLeft
offsetTop
它们指定元素相对于其最近的具有布局的父元素的位置。通常可以通过offsetParent属性访问此父级。
IE和FF3具有
clientLeft
clientTop
这些财产不太常见,它们使用其父工作区指定元素位置(填充区是工作区的一部分,但边界和边距不是)。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用域集图例引导
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 音频停止功能
- 有Grunt生成index.html不同的设置
- 如何禁用谷歌翻译从HTML在Chrome
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 向HTML表中添加水平滚动条