如何解决透明菜单到滚动的彩色菜单
我绝对是 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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。