首页 > 解决方案 > 滚动上的透明菜单到彩色菜单

问题描述

我绝对是 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;
}

标签: javascripthtmlcssscrollmenu

解决方案


  • 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>


推荐阅读