Wal*_*ssa 152 javascript
我想得到一个元素相对于浏览器视口的位置(显示页面的视口,而不是整个页面).如何在JavaScript中完成?
非常感谢
Him*_*u P 264
现有答案现已过时.本机getBoundingClientRect()方法已经存在了很长一段时间,并且正是问题所要求的.此外,它支持所有浏览器(包括IE 5,似乎!)
来自MDN页面:
返回的值是一个TextRectangle对象,它包含描述border-box的只读左,上,右和底属性,以像素为单位,左上角相对于视口的左上角.
你这样使用它:
var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;
Run Code Online (Sandbox Code Playgroud)
Fab*_*sco 42
在我的情况下,为了安全滚动,我添加了window.scroll到等式:
var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;
Run Code Online (Sandbox Code Playgroud)
这使得我可以获得元素在文档上的真实相对位置,即使它已被滚动.
Der*_*ley 15
编辑: 添加一些代码以考虑页面滚动.
function findPos(id) {
var node = document.getElementById(id);
var curtop = 0;
var curtopscroll = 0;
if (node.offsetParent) {
do {
curtop += node.offsetTop;
curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
} while (node = node.offsetParent);
alert(curtop - curtopscroll);
}
}
Run Code Online (Sandbox Code Playgroud)
id参数是您想要的偏移量的元素的id.改编自quirksmode帖子.
小智 10
var element = document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
elemRect = element.getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
Run Code Online (Sandbox Code Playgroud)
jQuery 非常优雅地实现了这一点。如果您查看 jQuery's 的源代码offset,您会发现这基本上是它的实现方式:
var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};
Run Code Online (Sandbox Code Playgroud)
function inViewport(element) {
let bounds = element.getBoundingClientRect();
let viewWidth = document.documentElement.clientWidth;
let viewHeight = document.documentElement.clientHeight;
if (bounds['left'] < 0) return false;
if (bounds['top'] < 0) return false;
if (bounds['right'] > viewWidth) return false;
if (bounds['bottom'] > viewHeight) return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
此页面上的函数将返回一个矩形,其中包含传递的元素相对于浏览器视口的顶部、左侧、高度和宽度坐标。
localToGlobal: function( _el ) {
var target = _el,
target_width = target.offsetWidth,
target_height = target.offsetHeight,
target_left = target.offsetLeft,
target_top = target.offsetTop,
gleft = 0,
gtop = 0,
rect = {};
var moonwalk = function( _parent ) {
if (!!_parent) {
gleft += _parent.offsetLeft;
gtop += _parent.offsetTop;
moonwalk( _parent.offsetParent );
} else {
return rect = {
top: target.offsetTop + gtop,
left: target.offsetLeft + gleft,
bottom: (target.offsetTop + gtop) + target_height,
right: (target.offsetLeft + gleft) + target_width
};
}
};
moonwalk( target.offsetParent );
return rect;
}
Run Code Online (Sandbox Code Playgroud)
你可以试试:
node.offsetTop - window.scrollY
它适用于Opera,并定义了视口元标记.
| 归档时间: |
|
| 查看次数: |
175514 次 |
| 最近记录: |