【发布时间】:2020-07-27 02:26:34
【问题描述】:
我想执行仅在满足以下 2 个条件时才会发生的侦听器函数(添加类“光标白色”)。
- $(window).scrollTop 为 0(在窗口顶部)
- 且窗口为
我正在努力使逻辑正确。我已将 mql 放在区间滚动函数中。它在满足 2 个条件时执行(并添加了类),这很好,但是当我从大于 900px 变为小于 900px 宽时它也会执行,即使滚动位置不在窗口的顶部。
这显然不是我们想要的结果。如何确保仅在满足这两个条件时才添加课程。非常感谢任何帮助:)
var didScroll;
$(window).scroll(function(event) {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
atTop();
didScroll = false;
}
}, 250);
function atTop(){
if ($(window).scrollTop() <= 0){
var x = window.matchMedia("(max-width: 900px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
function myFunction(e) {
if (e.matches) {
if($('.logo').hasClass('invert')){
$(".header-fixed").addClass("cursor-white");
}
} else{
$(".header-fixed").removeClass("cursor-white")
}
}
}
else {
$(".header-fixed").removeClass("cursor-white");
}
}
【问题讨论】:
标签: jquery scroll listener scrolltop matchmedia