我可以在 scrolltop 中使用百分比作为值吗?
Can i use a percentage as a value in scrolltop?
总的来说,我对 HTML 还很陌生。我有以下代码,我想知道是否有任何方法可以使用百分比而不是固定值。我已经搜索过,但找不到简单的解决方案。
$(window).scroll(function () {
if ($(this).scrollTop() > 445 && $(this).scrollTop() < 1425 ) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
基本上我想要的是 class 在滚动到页面的 80% 之后被删除,而不是在 1425px 之后,这样即使 window 大小被修改它也能正常工作。
根据文档,scrollTop() 需要一个代表像素位置的数字。
但是您可以计算滚动条何时达到 80%,例如,
伪代码:
if ((this.scrollTop + this.height) / content.height >= .8){
// do something
}
例如,请参阅下面的工作代码段
$("#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>
更新!我最终使用 $(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");
}
});
无论如何,感谢您的帮助,我希望有人能发现这有用!
总的来说,我对 HTML 还很陌生。我有以下代码,我想知道是否有任何方法可以使用百分比而不是固定值。我已经搜索过,但找不到简单的解决方案。
$(window).scroll(function () {
if ($(this).scrollTop() > 445 && $(this).scrollTop() < 1425 ) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
基本上我想要的是 class 在滚动到页面的 80% 之后被删除,而不是在 1425px 之后,这样即使 window 大小被修改它也能正常工作。
根据文档,scrollTop() 需要一个代表像素位置的数字。
但是您可以计算滚动条何时达到 80%,例如,
伪代码:
if ((this.scrollTop + this.height) / content.height >= .8){
// do something
}
例如,请参阅下面的工作代码段
$("#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>
更新!我最终使用 $(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");
}
});
无论如何,感谢您的帮助,我希望有人能发现这有用!