Javascript 如何获得元素与顶部的距离?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11805955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the distance from the top for an element?
提问by Sami Al-Subhi
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.
我想知道如何使用 JavaScript 来获取元素与页面顶部的距离,而不是父元素。
回答by Shawn Whinnery
offsetTop only looks at the element's parent. Just loop through parent nodes until you run out of parents and add up their offsets.
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 };
}
回答by eeglbalazs
var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top
In my experience document.body.scrollTop
doesn't always return the current scroll position (for example if the scrolling actually happens on a different element).
根据我的经验document.body.scrollTop
,并不总是返回当前滚动位置(例如,如果滚动实际上发生在不同的元素上)。
回答by www139
Here is some interesting code for you :)
这是一些有趣的代码给你:)
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>
回答by Kelvin Jardin
var distanceTop = element.getBoundingClientRect().top;
For details vist a link:
有关详细信息,请访问链接:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
回答by Thankgod Ossaija
offsetTop doesn't get the distance to the top of the page, but rather to the top of the closest parent element that has a specified position.
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.
您可以使用一种简单的技术,将您感兴趣的元素的所有父元素的 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;
Original code from https://gomakethings.com/how-to-get-an-elements-distance-from-the-top-of-the-page-with-vanilla-javascript/
回答by Aras Ksgl
scroll to element's top position;
滚动到元素的顶部位置;
var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;
回答by sajad saderi
it's so easy just do this :
这样做很简单:
select your element
选择你的元素
let distance_fromTop = document.getElementById("ID_NAME").offsetTop;
distance_fromTop will be Distance of the element from top of window then you can easily scroll to this part of window
distance_fromTop 将是元素与窗口顶部的距离,然后您可以轻松滚动到窗口的这一部分
with this code
用这个代码
window.scrollTo( 0 , distance_fromTop );
a piece of cake :)
一块蛋糕 :)
your code must be like this
你的代码必须是这样的
let distance_fromTop = document.getElementById("ID_NAME").offsetTop;
window.scrollTo( 0 , distance_fromTop );
回答by Ezra Siton
warning
warning
warning
warning
warning
warning
warning
warning
warning
warning
warning
warning
"Classic case" - URL "/#about-us" and div with an id of "about-us". In this case, the top position set by default anchor click behavior(So the top is 0for about-us
div). You mustprevent default (Or you'll go crazy for why it doesn't work -or- any other code you find out there). More details below under "warning".
"经典案例" - URL " /#about-us" 和 id 为"about-us" 的div 。在这种情况下,默认锚点点击行为设置的顶部位置(因此顶部为0为about-us
div)。你必须防止默认(否则你会为它为什么不起作用而发疯——或者你在那里发现的任何其他代码)。以下“警告”下的更多详细信息。
1
1
Less than 30 seconds solution (Two lines of code "hello world"):
30秒以内解决方案(两行代码“hello world”):
get your element:
获取您的元素:
var element = document.getElementById("hello");
Get getBoundingClientRect ();
获取 getBoundingClientRect();
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport. https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
var rect = element.getBoundingClientRect();
Return object:
返回对象:
Dot notation top
点符号 top
var distance_from_top = rect.top; /* 1007.9971313476562 */
Thats it.
就是这样。
2
2
StackOverflow nightmare 2 - set scroll position to this value
StackOverflow 噩梦 2 - 将滚动位置设置为此值
Again "hello world" (8,000 answers out there - 7,999 not working or to complex).
再次“你好世界”(有 8,000 个答案 - 7,999 个无效或复杂)。
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});
Add offset value to top
if you want (For sticky navbars).
top
如果需要,可以添加偏移值(对于粘性导航栏)。
"Hello World" code snippet (Get distance from top viewport + click to scrollTo
)
“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
warning
scrollTo "conflict" with main anchor navbars
scrollTo 与主锚导航栏“冲突”
This trick is very buggyif, for example, you use this URL (ID to anchor URL)(Top is 0
or "get crazy" hh).
这招是非常马车如果,例如,你可以使用这个URL(ID来锚URL)(顶部0
或“抓狂” HH)。
www.mysite/about#hello
window.scrollTo({
top: element.getBoundingClientRect().top,
behavior: 'smooth'
});
For this code to work you should add:
要使此代码正常工作,您应该添加:
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
Basic example her: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp
她的基本例子:https: //www.w3schools.com/howto/howto_css_smooth_scroll.asp
回答by CodeMonk
Although it is quite an old discussion, but this works pretty well on chrome / firefox / safari
browsers:
虽然这是一个相当古老的讨论,但这在chrome / firefox / safari
浏览器上非常有效:
window.addEventListener('scroll', function() {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
});
Check it out on JSFiddle