我想知道如何在JavaScript中获取img和div等HTML元素的X和Y位置。
当前回答
这样怎么样,通过传递元素的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');
其他回答
大多数浏览器上的HTML元素将具有:-
offsetLeft
offsetTop
它们指定元素相对于其最近的具有布局的父元素的位置。通常可以通过offsetParent属性访问此父级。
IE和FF3具有
clientLeft
clientTop
这些财产不太常见,它们使用其父工作区指定元素位置(填充区是工作区的一部分,但边界和边距不是)。
您可以将两个财产添加到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/
我想我也会把这个扔出去。我还不能在旧版浏览器中测试它,但它在前3名中的最新版本中运行。:)
Element.prototype.getOffsetTop = function() {
return ( this.parentElement )? this.offsetTop + this.parentElement.getOffsetTop(): this.offsetTop;
};
Element.prototype.getOffsetLeft = function() {
return ( this.parentElement )? this.offsetLeft + this.parentElement.getOffsetLeft(): this.offsetLeft;
};
Element.prototype.getOffset = function() {
return {'left':this.getOffsetLeft(),'top':this.getOffsetTop()};
};
获取div相对于左侧和顶部的位置
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
如果页面至少包含任何“DIV”,meouw给出的函数会将“Y”值抛出到当前页面限制之外。为了找到准确的位置,您需要处理offsetParent和parentNode。
尝试以下代码(检查FF2):
var getAbsPosition = function(el){
var el2 = el;
var curtop = 0;
var curleft = 0;
if (document.getElementById || document.all) {
do {
curleft += el.offsetLeft-el.scrollLeft;
curtop += el.offsetTop-el.scrollTop;
el = el.offsetParent;
el2 = el2.parentNode;
while (el2 != el) {
curleft -= el2.scrollLeft;
curtop -= el2.scrollTop;
el2 = el2.parentNode;
}
} while (el.offsetParent);
} else if (document.layers) {
curtop += el.y;
curleft += el.x;
}
return [curtop, curleft];
};
推荐文章
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 我如何在网站上使用谷歌的Roboto字体?
- 父ng-repeat从子ng-repeat的访问索引
- 如何禁用文本区域大小调整?
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 保留HTML字体大小时,iPhone的方向从纵向改变为横向
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 如何把滚动条只为情态体?