我可以在 scrolltop 中使用百分比作为值吗?

Jan*_*Gil 5 html javascript jquery scroll scrolltop

总的来说,我对 HTML 很陌生。我有以下代码,我想知道是否有任何方法可以使用百分比而不是固定值。我已经搜索过,但找不到简单的解决方案。

$(window).scroll(function () { 
    if ($(this).scrollTop() > 445 && $(this).scrollTop() < 1425 ) { 
        nav.addClass("f-nav");
    } else { 
        nav.removeClass("f-nav");
    } 
Run Code Online (Sandbox Code Playgroud)

基本上我想要的是在滚动超过页面的 80% 后删除的类,而不是在 1425px 之后,以便在修改窗口大小时它也能正常工作。

scr*_*ppy 6

从文档中,scrollTop()需要一个表示像素位置的数字。

但是您可以计算滚动达到 80% 的时间,例如,

伪代码:

if ((this.scrollTop + this.height) / content.height >= .8){
// do something
}
Run Code Online (Sandbox Code Playgroud)

例如,请参阅下面的工作片段

if ((this.scrollTop + this.height) / content.height >= .8){
// do something
}
Run Code Online (Sandbox Code Playgroud)
$("#container").scroll(function () { 
    if (($(this).scrollTop()+$(this).height())/$("#content").height() >= .8) { 
        $("#content").addClass("scrolled");
     }else{
       $("#content").removeClass("scrolled");
     }
     });
Run Code Online (Sandbox Code Playgroud)
#container{
  width:80%;
  height:300px;
  border: solid 1px red;
  overflow:auto;
}

#content{
  width:80%;
  height:1000px;
  border: solid 1px gray;
  transition: background-color 1s;
}
#content.scrolled{
  background-color:blue;
}
Run Code Online (Sandbox Code Playgroud)