gpt4 book ai didi

javascript - 计算已滚动到 View 中的特定元素的百分比

转载 作者:行者123 更新时间:2023-11-30 08:25:13 25 4
gpt4 key购买 nike

假设您有一个包含多个大面板的网页,您可以使用以下代码轻松计算出用户滚动到整个页面的百分比。

$(window).scroll(function(){

var windowTop = $(this).scrollTop()
var bodyHeight = $('body').height()

var percentage = (windowTop/bodyHeight) * 100
console.log(percentage)

});

但是我想要做的是计算,对于一个单独的面板,该面板的 百分比已滚动到视口(viewport)中。因此,在您到达面板之前,这将始终为 0%,一旦您滚动到该面板的底部,它将为 100%。

我觉得这可能是一个简单的方程式,但我无法全神贯注地思考实现这一目标需要做些什么。

最佳答案

这是一个构造函数,它可以监视给定的元素并返回一个关于屏幕百分比的数据对象。它监视视口(viewport)上方和下方的元素。

var OnScreenPercentage = function(querySelector, callback){
var self = this;
this.callback = callback;
this.elements = querySelector?$(querySelector):[];

this.remove = function(){
if(this.handler){
$(window).off("scroll", this.handler);
}
}
var calcTop = function(rect, win){
return Math.max(rect.height+rect.y, 0)/rect.height;
}
var calcBottom = function(rect, win){
return Math.max(win.height-rect.y, 0)/rect.height;
}
var calcPercentages = function(){
var win = {height: $(window).height()};
for(var e=0; e<self.elements.length; ++e){
var rect = self.elements[e].getBoundingClientRect();
self.callback({
element: self.elements[e],
percentage: rect.y<0 ? calcTop(rect, win) : (rect.y+rect.height)>win.height ? calcBottom(rect, win) : 1,
location: rect.y<0 ? 'top' : (rect.y+rect.height)>win.height ? 'bottom' : 'middle'
});
}
}
this.handler = $(window).scroll(calcPercentages);
calcPercentages();
}

//Example usage
var onScreen = new OnScreenPercentage('.box', function(data){
var percent = $(data.element).find('.percentage');
$(percent).width(100*data.percentage+'%');
if(data.location=='top'||data.location=='middle'){
$(percent).css({left:'0', right: ''});
}else{
$(percent).css({left:'', right:'0'});
}
});
.box {
height: 100px;
line-height: 100px;
background-color: rgba(0,0,0,0.1);
margin: 5px;
position: relative;
color: #fff;
font-size: 30px;
text-align: center;
}
.percentage {
background: #00F;
position: absolute;
top: 0;
bottom: 0;
z-index: -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box">Box 0 <div class="percentage"></div></div>
<div class="box">Box 1 <div class="percentage"></div></div>
<div class="box">Box 2 <div class="percentage"></div></div>
<div class="box">Box 3 <div class="percentage"></div></div>
<div class="box">Box 4 <div class="percentage"></div></div>
<div class="box">Box 5 <div class="percentage"></div></div>
<div class="box">Box 6 <div class="percentage"></div></div>
<div class="box">Box 7 <div class="percentage"></div></div>
<div class="box">Box 8 <div class="percentage"></div></div>

关于javascript - 计算已滚动到 View 中的特定元素的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46851076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com