gpt4 book ai didi

Javascript仅适用于滚动事件?

转载 作者:行者123 更新时间:2023-11-28 04:29:23 24 4
gpt4 key购买 nike

是否可以创建一个极简的javasript only 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 */

关于Javascript仅适用于滚动事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com