javascript - 滚动上的透明菜单到彩色菜单
问题描述
我绝对是 js 的初学者,我想要一个透明菜单,当向下滚动时,会发生从透明到带有框阴影的平滑过渡。但是代码js不起作用
<script type="text/javascript">
var a=document.getElementById('play');
var x=window.pageYOffset;
var see =function () {
if (x >30) {
a.style.background=" white";
}else{
a.style.background="transparent";
}
window.addEventListener("onscroll",see);
}
</script>
<header>
<div class="menu" id='a'>
<ul>
<li><b>About</b></li>
</ul>
</div>
</header>
.menu {
background: transparent;
margin-left: 320px;
text-align: center;
width: 100%;
padding: 20px;
position: fixed;
top: 0px;
transition: .5s;
}
解决方案
- 将
x
定义放在see
函数内 - 放在
window.addEventListener("onscroll",see);
后面!(外)see
函数 - 使用
"scroll"
事件名称
var a = document.getElementById('play');
function see() {
var x = window.pageYOffset; // This one goes inside
if (x > 30) {
a.style.background = " white";
} else {
a.style.background = "transparent";
}
}
window.addEventListener("scroll", see); // This one goes outside
此外,样式应该进入 CSS,而不是分散在您的 JS 文件中。
使用 Element.classList.toggle() 切换预定义的 CSS 类:
const EL_play = document.querySelector("#play");
function see() {
var x = window.pageYOffset; // This one goes inside
EL_play.classList.toggle("is-active", x > 30);
}
window.addEventListener("scroll", see); // This one goes outside
body {
margin: 0;
}
#play {
position: sticky;
top: 0;
width: 100%;
transition: background-color 0.3s;
}
#play.is-active {
background-color: gold;
}
<div id="play">PLAY</div>
<p style="height: 300vh;">Long element to force scrollbars...</p>
推荐阅读
- office-js - 在 Outlook 加载项中发出 API 请求时出错
- amazon-web-services - S3/CloudFront DNS 主机不会仅在韩国 IP 中更新
- javascript - 如何将表单值修补到递归嵌套的 Angular 表单?
- c++ - 仅在 MacOS 上用于析构函数的未定义符号
- python - 使用 pyautogui 和数学在油漆中绘制棕褐色波
- amazon-web-services - 是否可以运行多个并行写入 S3 的 Spark Structured Streaming 作业?
- node.js - 为什么流式传输响应比在 Node.js / Express 中发送常规响应慢得多?
- html - 导航栏中的 Flexbox:无法垂直对齐项目
- c - 为什么向内联函数添加声明会生成符号?
- c# - Javascript sweetalert 插件总是显示一个输入文本框