How to get the distance from the top for an element?

I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
enter image description here

http://jsfiddle.net/yZGSt/1/

149177 次浏览

Use offsetTop

document.getElementById("foo").offsetTop

演示

使用 jQuery 的 offset()方法:

$(element).offset().top

例子: http://jsfiddle.net/yZGSt/3/

OffsetTop 只查看元素的父元素。只需循环遍历父节点,直到用完父节点并添加它们的偏移量。

function getPosition(element) {
var xPosition = 0;
var yPosition = 0;


while(element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}


return { x: xPosition, y: yPosition };
}

更新: 这个答案有一些问题,值将有微小的差异相比,它应该是,并不会在某些情况下正常工作。

检查 @ eeglbalazs 的回答,这是准确的。

(来源: 使用 javascript 确定从 div 顶部到窗口顶部的距离)

<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar");  //your element
var EnableConsoleLOGS = true;                          //to check the results in Browser's Inspector(Console), whenever you are scrolling






// ==============================================
window.addEventListener('scroll', function (evt) {
var Positionsss =  GetTopLeft ();
if (EnableConsoleLOGS) { console.log(Positionsss); }
});
function GetOffset (object, offset) {
if (!object) return;
offset.x += object.offsetLeft;       offset.y += object.offsetTop;
GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
if (!object) return;
scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html") {          GetScrolled (object.parentNode, scrolled);        }
}


function GetTopLeft () {
var offset = {x : 0, y : 0};        GetOffset (myyElement, offset);
var scrolled = {x : 0, y : 0};      GetScrolled (myyElement.parentNode, scrolled);
var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>

这里有一些有趣的代码:)

window.addEventListener('load', function() {
//get the element
var elem = document.getElementById('test');
//get the distance scrolled on body (by default can be changed)
var distanceScrolled = document.body.scrollTop;
//create viewport offset object
var elemRect = elem.getBoundingClientRect();
//get the offset from the element to the viewport
var elemViewportOffset = elemRect.top;
//add them together
var totalOffset = distanceScrolled + elemViewportOffset;
//log it, (look at the top of this example snippet)
document.getElementById('log').innerHTML = totalOffset;
});
#test {
width: 100px;
height: 100px;
background: red;
margin-top: 100vh;
}
#log {
position: fixed;
top: 0;
left: 0;
display: table;
background: #333;
color: #fff;
}
html,
body {
height: 2000px;
height: 200vh;
}
<div id="log"></div>
<div id="test"></div>

var distanceTop = element.getBoundingClientRect().top;

详情请访问链接:

Https://developer.mozilla.org/en-us/docs/web/api/element/getboundingclientrect

虽然这是一个相当老的讨论,但这在 chrome / firefox / safari浏览器上运行得很好:

window.addEventListener('scroll', function() {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
});

看看 JSFiddle频道

var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top

根据我的经验,document.body.scrollTop并不总是返回当前的滚动位置(例如,如果滚动实际上发生在不同的元素上)。

OffsetTop 不获取到页面顶部的距离,而是到具有指定位置的最接近的父元素的顶部的距离。

You can use a simple technique that adds up the offsetTop of all the parent element of the element you are interested in to get the distance.

// Our element
var elem = document.querySelector('#some-element');


// Set our distance placeholder
var distance = 0;


// Loop up the dom
do {
// Increase our distance counter
distance += elem.offsetTop;


// Set the element to it's parent
elem = elem.offsetParent;


} while (elem);
distance = distance < 0 ? 0 : distance;

https://gomakethings.com/how-to-get-an-elements-distance-from-the-top-of-the-page-with-vanilla-javascript/的原始代码

滚动到元素的顶部位置;

var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;

warning warning warning warning warning warning

“ Classic case”-URL“ 关于我们”和 id 为 “关于我们”的 div。在本例中,顶部位置由 默认锚点击行为设置(因此,对于 about-us div,顶部是 0)。你的 必须的防止默认(或者你会发疯为什么它不工作-或-任何其他代码你找到了)。更多详情见下文“警告”一栏。

1

不到30秒的解决方案(两行代码“ hello world”) :

掌握你的元素:

var element = document.getElementById("hello");

获取 getBoundingClientRect () ;

Getbound ingClientRect ()方法返回 元素及其相对于视口的位置。 < a href = “ https://developer.mozilla.org/en-US/docs/Web/API/Element/getbound ingClientRect”rel = “ nofollow norefrer”> https://developer.mozilla.org/en-us/docs/web/api/element/getboundingclientrect

var rect = element.getBoundingClientRect();

返回对象:

enter image description here

点符号 top

var distance_from_top = rect.top; /* 1007.9971313476562 */

就是这样。

2

StackOverflow 噩梦2-将滚动位置设置为此值

同样是“ hello world”(外面有8000个答案——7999个不起作用或者很复杂)。

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

  window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});

如果需要,可以将偏移量值添加到 top(用于粘性导航栏)。

“ Hello World”代码片段(从顶部视图获取距离 + 单击 scrollTo)

var element = document.getElementById("hello");
var rect = element.getBoundingClientRect();
var distance_from_top = rect.top; /* 50px */
console.log(distance_from_top);


function scrollTovView(){
window.scrollTo({
top: distance_from_top,
behavior: 'smooth'
});
}
div{
text-align:center;
border: 1px solid lightgray;
}
<button onclick="scrollTovView()">scrollTo to red DIV</button>
<div style="height: 50px;">50px height</div>
<div id="hello" style="width: 500px; height: 500px; background: red;"></div>

warning

与主锚导航栏“冲突”

例如,如果您使用这个 URL (ID 到锚 URL)(顶部是 0或“ get crazy”hh) ,那么这个技巧非常 马车

www.mysite/about#hello
  window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});

为了让这段代码正常工作,您应该添加:

    if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();

她的基本例子是: Https://www.w3schools.com/howto/howto_css_smooth_scroll.asp

This function returns distance from top of the page, even if your window is scrolled. It can be used in event listeners.

const getElementYOffset = (element) => {
const scrollOnWindow =
window.pageYOffset !== undefined
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollTop;
const rect = element.getBoundingClientRect();
let distanceFromTopOfPage = rect.top;
if (scrollOnWindow !== 0) {
distanceFromTopOfPage = rect.top + scrollOnWindow;
}


return distanceFromTopOfPage;
};

这个线条看起来不错

document.getElementById("el").getBoundingClientRect().top +  window.scrollY

你的小提琴更新了

你只需要这条线

document.getElementById("el").getBoundingClientRect().top

其中“ el”是元素。

document.getElementById("id").offsetTop

由于 window.pageYOffsetwindow.scrollY的遗留别名,eeglbalazs 的答案可以改进为:

const elDistanceToTop = window.scrollY + el.getBoundingClientRect().top;