我有一个功能完美的元素,其行为符合预期。一旦用户滚动到特定点,就会添加一个类。当用户向上滚动时,该类将被删除。我的问题是,一旦添加了该类,当我刷新页面时,将不再添加该类,直到我再次滚动。
这是间歇性的。 Firefox 是持续产生该问题的主要浏览器。 Chrome 打开和关闭。
我已经包含了一个非常简化的代码片段,但是不容易看到,因为它需要刷新。我搜索了一整天,查看了 cookies、本地存储、classie.js。我确信有比这些更简单、更简单的解决方案。
这是一个有类似问题的网站:https://bert.house/en/ .请在 Firefox 中检查。页面左上角的导航按钮,向下滚动,看看会发生什么。然后刷新,你会看到它回到原来的状态,直到你再次滚动。
$(window).scroll(function() {
var box = $('.box');
var scroll = $(window).scrollTop();
if (scroll > 100) {
box.removeClass('box-NotScrolled');
box.addClass('boxScrolled');
} else {
if (box.hasClass('boxScrolled')) {
box.removeClass('boxScrolled');
box.addClass('box-NotScrolled');
}
}
});
.box {
position: fixed;
top: 5%;
left: 5%;
width: 200px;
height: 200px;
background-color: red;
}
.boxScrolled {
background-color: green;
}
.box-NotScrolled {
background-color: red;
}
<div class="box"></div>
<div style="height: 1000px"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这不是什么大问题。这是一个困扰我的问题,因为必须有一个解决方法。任何帮助都会很棒。谢谢。
最佳答案
这将在您加载脚本以及滚动或调整大小时运行。这实际上会在页面加载时为您检查。
//Create classOnScroll function
function classOnScroll(){
let $box = $('.box'),
$scroll = $(window).scrollTop();
if($scroll > 100){
if(!$box.hasClass('boxScrolled'))
$box.addClass('boxScrolled');
}
else
$box.removeClass('boxScrolled');
}
//Run on first site run
classOnScroll();
//Run on scroll and resize
$(window).on('scroll resize',classOnScroll);
.box {
position: fixed;
top: 5%;
left: 5%;
width: 200px;
height: 200px;
background-color: red;
}
.boxScrolled {
background-color: green;
}
<div class="box"></div>
<div style="height: 1000px"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于jquery - 刷新页面后在滚动上添加类并保持行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179467/