javascript - 在滚动上添加类不起作用?

标签 javascript jquery html

所以,我本质上是在尝试从 this website 中提取(以尽可能粗略的方式) header 。 。他们所做的是,当用户滚动到> 0 的位置时,他们添加一个额外的类。我认为这很简单,但 java 总是有办法给我带来问题。我想出了以下代码:

<!DOCTYPE html>
<html>

<head>
</head>
<style>
  body {
    height: 5000px;
  }
  #scroll {
    position: fixed;
    height: 50px;
    width: 100%;
  }
  .box {
    background-color: orange;
    color: white
  }
  .test {
    background-color: red;
    color: pink;
  }
</style>
<script>
  window.onscroll = function() {
    myFunction();
  };

  function myFunction() {
    if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
      document.getElementById("scroll").className = "test";
    } else {
      document.getElementById("scroll").className = "";
    }
  }
</script>

<body>

  <div class="box" id="scroll">THIS ISNT WORKING</div>

</body>

</html>

当我向下滚动时,该类适用,但当我向上滚动时,该类不适用。有什么想法吗?

最佳答案

这是 secret ,在这一行:

document.getElementById("scroll").className = "";

您没有将其设置回旧的类box,因此当滚动回顶部时它没有类。像这样更改它:

  function myFunction() {
    if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
      document.getElementById("scroll").className = "test";
    } else {
      document.getElementById("scroll").className = "box";
    }
  }

演示:

<!DOCTYPE html>
<html>

<head>
</head>
<style>
  body {
    height: 5000px;
  }
  #scroll {
    position: fixed;
    height: 50px;
    width: 100%;
  }
  .box {
    background-color: orange;
    color: white
  }
  .test {
    background-color: red;
    color: pink;
  }
</style>
<script>
  window.onscroll = function() {
    myFunction();
  };

  function myFunction() {
    if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
      document.getElementById("scroll").className = "test";
    } else {
      document.getElementById("scroll").className = "box";
    }
  }
</script>

<body>

  <div class="box" id="scroll">THIS ISNT WORKING</div>

</body>

</html>

关于javascript - 在滚动上添加类不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843712/

相关文章:

jquery - 如何捕获 jQuery 的 load() 方法中的错误

javascript - 如何重新加载 jquery 以便它适用于下一个进程

javascript - 如果任何特定的 div 具有特定的图像,如何显示任何 div

javascript - 在使用 PKCE 的 OAuth 授权流程中使用时,如何在 Azure 应用程序注册中启用 CORS?

javascript - jQuery 隐藏和仅显示源文件

javascript - Range = document.getSelection().getRangeAt(0) 在 Safari 上不起作用

javascript - 合并两个代码片段?将用户输入的 Youtube url 转换为嵌入 url,然后用转换后的 url 替换 iframe src

javascript - Google 电子表格侧边栏中的表单处理和验证

Javascript 从另一个字段设置隐藏字段值在移动设备上不起作用

jquery - 通过 jQuery 触发时 CSS3 转换最初不起作用