[英]How do I get the percentage of an element's current position relative to the window?
I'm trying to return an element's position as a percentage based on where the element is in the window using jquery.我正在尝试根据元素在 window 中的位置使用 jquery 以百分比的形式返回元素的 position。
$(window).on('resize scroll', function() {
var docHeight = (function(){
return Math.max(
$(document).height(),
$(window).height()
);
})();
var percent = (($(element).offset().top / docHeight) * 100);
console.log(percent);
});
I'm expecting the console to log the percentage of where the top of the element is in the window, ie if the element's top is at the bottom of window, the percentage is 0%, if the element's top is in the middle of the window, the percentage is 50%, etc. However, it is returning the position as a percentage in relation to the document and does not change when you scroll.我希望控制台记录元素顶部在 window 中的位置的百分比,即如果元素顶部位于 window 的底部,则百分比为 0%,如果元素顶部位于 window 的中间window,百分比为 50%,等等。但是,它以相对于文档的百分比形式返回 position,并且在您滚动时不会更改。
Probably wanna take a look at Element.getBoundingClientRect() . 可能想看看Element .get Bounding Client Rect() 。
Returns information about an element's position. 返回有关元素位置的信息。
Using getBoundindClientRect to get the element's position and innerHeight to get the viewport height, you can calculate the element's relative position:使用getBoundindClientRect获取元素的 position 和innerHeight获取视口高度,可以计算出元素的相对 position:
$(window).scroll(function(){
var elem = document.getElementById("myElement"),
rect = elem.getBoundingClientRect(),
pct = (window.innerHeight-rect.top)/window.innerHeight;
console.log(pct);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.