如何检测用户是否从当前位置滚动了 100px



>我有一个单页网站,当用户点击导航时,我正在添加一个类。但是,如果用户从当前位置滚动100px,则需要删除该类。

演示 GH 页面链接

//working fine
var scrollvalue = 0;
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
scrollvalue = $(window).scrollTop();
$(".copyright").addClass("activecopy");
});
//not working fine
$(window).scroll(function() {
if($(window).scrollTop() > 100) {
$('.copyright').removeClass('activecopy');
}
});

注意:我已经阅读了堆栈溢出帖子,例如 post1 和 post2

要弄清楚问题到底是什么有点困难,因为您没有共享相应的 HTML 标记。请尝试以下操作,让我知道是否有帮助。

var scrollvalue = 0;
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function () {
scrollvalue = $(window).scrollTop();
$(".copyright").addClass("activecopy");
});

$(window).scroll(function () {
if (($(window).scrollTop() - scrollvalue) > 100) {
$('.copyright').removeClass('activecopy');
}
});

编辑:

正如我所说,很难看到发生了什么,因为您没有共享标记。下面是一个示例。希望对您有所帮助。

编辑2:

要使其通用,您可以将注册单击侦听器和滚动侦听器的代码包装在一个函数中,该函数接受要操作的元素作为参数。示例如下。

function registerScrollTrigger(anchor, target) {
var $a = $(anchor);
var $t = $(target);
$a.click(function() {
//Get scroll position at the time of the click
var currentScroll = $(window).scrollTop();
function handleScroll() {
// Demo code to show current scroll on the screen
$t.html('Current Scroll: ' + ($(window).scrollTop() - currentScroll));
// Check if the user has scrolled 100px since clicking the tag
if (($(window).scrollTop() - currentScroll) > 100) {
// Remove active class from element
$t.removeClass('active');
// Demo code ti indicate that the scroll to 100px is complete
$t.html('Complete');
// Stop listening for scroll events [Optional but recommmended]
$(window).off('scroll', handleScroll);
}
}
// Add active class to element [Make it blue]
$t.addClass('active');
// Listen for scroll event and check if 100px has passed
$(window).scroll(handleScroll);
});
}
registerScrollTrigger('#a1', '#scroll1');
registerScrollTrigger('#a2', '#scroll2');
div.scroll {
margin-top: 50px;
}
div.scroll.active {
background: blue;
color: white;
}
div#pad {
height: 1000px;
}
h4 {
margin-bottom: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h4>Scroll Down For the Button</h4>
<a id="a1" class="js-scroll">Click Me </a>
<div id="scroll1" class="scroll">
Start scrolling after clicking the above button
</div>
<h4>Scroll Down For Another Button</h4>
<a id="a2" class="js-scroll">Click Me Too</a>
<div id="scroll2" class="scroll">
Start scrolling after clicking the above button
</div>
<div id="pad"></div>

注意:

您还可以通过在锚点上设置data-target属性来执行类似操作,该属性可用于确定要将类添加到哪个项目并从中删除该类,而不是将这两个项目作为参数传递

$(window).scroll(function() {
var height = $(window).scrollTop();
if (height > 100) {
$(".copyright").addClass("activecopy");
} else {
$('.copyright').removeClass('activecopy');
}

});

我正在使用它来在底部显示我的gototop按钮。希望这对你有用.....

最新更新