javascript - 如何根据滚动位置触发或停止 jQuery 函数?

标签 javascript jquery html css

我在一个有标题的网站上工作,当 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;
}

最佳答案

您可以使用 Intersection Observer 而不是监听滚动事件为了这。

Based on this example我为你创建了一个 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>

关于javascript - 如何根据滚动位置触发或停止 jQuery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177178/

相关文章:

javascript数学函数: Right now it forms a circle,我需要做一个半圆

javascript - Javascript 可以调用 Django 方法/函数吗?

jquery - 基于导航栏淡入淡出 DIV

javascript - 如何解决“未定义的错误 "Uncaught TypeError: Cannot call method 'changePage”

javascript - 从特定输入增加字母表

javascript - 使用 RESTful API 通过 Angular、ng-file-upload 异步上传文件

javascript - $(文档).ready(函数(){});页面底部的vs脚本

javascript - 使用 jQuery 按字母顺序对列表项进行排序 - 然后按数字对特殊项进行排序

javascript - 如果 .js 文件不存在,则包含 jQuery

css - HTML 5 拖放多个图像