是否可以创建一个极简主义的javasript仅滚动功能来隐藏我的菜单栏,因此仅显示菜单按钮,并且按钮本身获得白色背景色?我一直在研究这个问题,我相信代码会相当糟糕。但是我对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 */