我想知道如何使用JavaScript从页面顶部而不是父元素获取元素的距离。
答案 0 :(得分:77)
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 };
}
答案 1 :(得分:10)
以下是一些有趣的代码:)
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>
&#13;
答案 2 :(得分:8)
答案 3 :(得分:5)
var distanceTop = element.getBoundingClientRect().top;
有关详细信息,请访问链接:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
答案 4 :(得分:5)
var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top
根据我的经验document.body.scrollTop
并不总是返回当前滚动位置(例如,如果滚动实际发生在不同的元素上)。
答案 5 :(得分:1)
(来源:Determine distance from the top of a div to top of window with javascript)
<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>
答案 6 :(得分:1)
offsetTop不会获得到页面顶部的距离,而是到具有指定位置的最接近的父元素的顶部的距离。
您可以使用一种简单的技术,将您感兴趣的元素的所有父元素的offsetTop加起来以获得距离。
// 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;
答案 7 :(得分:1)
滚动到元素的顶部;
var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;
答案 8 :(得分:1)
很容易 只是这样做:
选择您的元素
speed * direction
distance_fromTop将是元素到窗口顶部的距离 那么您可以轻松滚动到窗口的这一部分
使用此代码
let distance_fromTop = document.getElementById("ID_NAME").offsetTop;
小菜一碟:)
您的代码必须是这样
window.scrollTo( 0 , distance_fromTop );
答案 9 :(得分:0)
warning
warning
warning
warning
warning
warning
“经典案例”-URL“ /#about-us”和div,其ID为“关于我们” 。在这种情况下,由默认锚点点击行为设置的最高位置(因此about-us
div的最高位置为 0 )。您必须阻止默认设置(否则,您会为默认设置无效而感到疯狂-或在那里找到任何其他代码)。下面在“警告”下有更多详细信息。
少于30秒的解决方案(两行代码“ hello world”):
var element = document.getElementById("hello");
Element.getBoundingClientRect()方法返回一个 元素及其相对于视口的位置。 https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
var rect = element.getBoundingClientRect();
返回对象:
top
var distance_from_top = rect.top; /* 1007.9971313476562 */
就这样。
再次出现“ hello world”(那里有8,000个答案-7,999个不起作用或很复杂)。
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});
根据需要向top
添加偏移值(对于粘性导航栏)。
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(用于锚定URL的ID)(顶部为0
或“发疯”……),此技巧非常笨拙。
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
答案 10 :(得分:0)
即使滚动窗口,此功能也会返回到页面顶部的距离。可以在事件侦听器中使用它。
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;
};
答案 11 :(得分:0)
这个oneliner似乎很好用
document.getElementById("el").getBoundingClientRect().top + window.scrollY
答案 12 :(得分:-1)
简单的香草方式:
document.querySelector('your-element').getBoundingClientRect().top
答案 13 :(得分:-1)
虽然这是一个相当古老的讨论,但这在chrome / firefox / safari
浏览器上运行良好:
window.addEventListener('scroll', function() {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
});
上查看
答案 14 :(得分:-9)