首页 > 解决方案 > 如何根据滚动位置触发或停止 jQuery 函数?

问题描述

我正在开发一个网站,该网站有一个标题,当该scrollTop()值超过浏览器高度的 1/4 时,根据用户是向上还是向下滚动,在屏幕上上下动画。对于主页,标题在所述scrollTop()值之后更改背景和文本颜色以适应视频背景。

但是,在滚动时headerScrollEvents()添加“显示”(标题向下滑动)、“隐藏”(标题向上滑动)和“活动”(标题更改背景和文本颜色)类的功能#header在滚动位置编号时仍在运行小于浏览器高度的 1/4。目标是防止用户从该scrollTop()值向上滚动到最顶部时添加这些类。

如何在到达某些滚动位置时触发或停止 jQuery 函数?

JS:

function headerScrollEvents() {

    var yPos = $(window).scrollTop();

    $(window).scroll(function() {
        var newYPos = $(this).scrollTop();
        if (newYPos > yPos) {
            $("#header").removeClass("show active").addClass("hide");
        } else {
            $("#header").removeClass("hide").addClass("show active");
        }

        yPos = newYPos;
    });

}

$(window).scroll(function() {

    if ( $(window).scrollTop() <= $(window).height() / 4 ) {
        $("#header").removeAttr("class");
    } else if ( $(window).scrollTop() >= $(window).height() / 4 ) {
        headerScrollEvents();
    }

});

CSS:

#header {
    top: 0;
    left: 0;
    position: fixed;
    width: 100%;
    z-index: 25;
    padding: 48px 0;
    transition: transform 500ms ease, background 500ms linear;
    background: #000;
}
#header.hide {
    transform: translateY(-100%);
}
#header.show {
    transform: translateY(0%);
}
#header.active {
    background: #fff;
}

标签: javascriptjqueryhtmlcss

解决方案


您可以使用Intersection Observer来代替监听滚动事件。

基于这个例子,我为你创建了一个 jsfiddle。我对其进行了修改以使您正在观看的 div 更大,以便更清楚它是如何工作的。您显然会将 div 的尺寸设置为 0px。

let observer = new IntersectionObserver(entries => {
  if (entries[0].boundingClientRect.y < 0) {
    console.log("Past the yellow div!");
  } else {
    console.log("Not past the yellow div");
  }
});
observer.observe(document.querySelector("#pixelToWatch"));
body {
  padding: 0;
  position: relative;
}

#pixelToWatch {
  position: absolute;
  width: 10px;
  height: 10px;
  top: 75%;
  left: 0;
  background: yellow;
}

header {
  position: fixed;
  width: 100%;
  background-color: green;
  top: 0;
}

section {
  padding-top: 100px;
  min-height: 200vh;
  background-image: linear-gradient(25deg, red, blue);
  color: white;
}
<header>
  <p>I'm a header </p>
</header>
<div id="pixelToWatch"> </div>

<section>
  <h1>I have a headline </h1>
  <p>
    And some content
  </p>
</section>
<section>
  <h1>I have a headline </h1>
  <p>
    And some content
  </p>
</section>


推荐阅读