【问题标题】:Can i use a percentage as a value in scrolltop?我可以在滚动顶部使用百分比作为值吗?
【发布时间】:2018-11-19 13:36:27
【问题描述】:

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

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

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

【问题讨论】:

  • 当页面小于窗口大小时,您无法滚动。所以我认为你的意思是在 80% 的滚动之后。看看这个答案:stackoverflow.com/questions/17688595/… 来计算最大 scrollTop 是多少。然后你可以检查scrollTop &gt; maxScrollTop * 0.8

标签: javascript jquery html scroll scrolltop


【解决方案1】:

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

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

伪代码:

if ((this.scrollTop + this.height) / content.height >= .8){
// do something
}

例如,请参阅下面的工作 sn-p

$("#container").scroll(function () { 
    if (($(this).scrollTop()+$(this).height())/$("#content").height() >= .8) { 
        $("#content").addClass("scrolled");
     }else{
       $("#content").removeClass("scrolled");
     }
     });
#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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="container">
  <div id="content"></div>
</div>

【讨论】:

  • 所以它应该是这样的? $(window).scroll(function () { if ($(this).scrollTop() > 445 && $(this).scrollTop() = .8){ nav.removeClass("f-nav");} }
  • 哎呀,我的错,无法在评论中按 Enter。但基本上把你说的“else”改了,对吧?
  • 不是我想要的,但它确实解决了我的问题,谢谢!
【解决方案2】:

更新!我最终使用了$(document).height() 而不是scrolltop,因为它让我可以轻松地引入百分比。所以我的代码最终看起来像这样:

$(window).scroll(function () { 
    if ($(this).scrollTop() > 445) { 
        nav.addClass("f-nav");
    if ($(this).scrollTop() > $(document).height()*0.64) 
        nav.removeClass("f-nav");
    }       
});

无论如何,感谢您的帮助,我希望有人能发现这很有用!

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 2016-03-30
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2017-12-27
    相关资源
    最近更新 更多