Javascript 只针对滚动事件?

Javascript only on scroll events?

是否可以创建一个极简的 javasript on-scroll 函数来隐藏我的菜单栏,这样只有菜单按钮显示并且按钮本身获得白色背景颜色?我一直在研究这个,我相信代码相当低。但我对 javasript 还很陌生,还不能完全理解它的语法。下面是我现在在 jsfiddle 中的内容:

https://jsfiddle.net/AngusBerry/zLt0yLou/2/#&togetherjs=Vsth32pa6L

html:

<!DOCTYPE html>

<body>
  <header>
    <h1><span id="tstscroll">0</span></h1>
    <div class="MenuButton" id="mobMenu"></div>
    <!--<p>as you can see, this is the header for the website. Here will also be contained all of the links to anywhere on the support system. this and the footer will both be FIXED and will move with the page.</p>-->
  </header>
</body>

css:

  header {
  top: 0px;
  position: fixed;
  max-height: 100px;
  width: 100%;
  padding-top: 2px;
  padding-bottom: 3.5px;
  color: green;
  animation: max-height-header;
  animation-duration: 1.5s;
}

header h1 {
  position: relative;
  float: left;
  margin-left: 3px;
}

header .MenuButton {
  width: 28px;
  height: 6px;
  border-top: 6px solid;
  border-bottom: 18px double;
  margin-right: 5px;
  margin-top: 2px;
}

javascript:

var mobilemenu = document.getElementById('mobMenu');
var testscroller = document.getElementById('tstscroll');
var x = 0;

document.mobilemenu.addEventListener("scroll", menuScrolMob);


function menuScrolMob(mobilemenu.onscroll) {
  testscroller.innerhtml = x += 1;
}

您需要 运行 该脚本要么在您的主体中,要么在页面加载之后,否则它将无法访问元素。

此外,您的脚本代码是错误的,所以这里有一个解决方案显示了如何解决这两个问题

(function(w, d) {        /* this is a closure and will keep its variables
                            from polluting the global namespace and it also
                            declare 2 variables (w, d) to be used inside it */

  w.addEventListener("load", function() {

    var mobilemenu = d.getElementById('mobMenu');
    var testscroller = d.getElementById('tstscroll');
    var x = 0;

    mobilemenu.addEventListener("scroll", function() {
      testscroller.innerhtml = x += 1;    
    });

  });

}(window, document));    /* here I pass the window and document object into the
                            closure's variables (w, d) to make the code slimmer  */