Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - Transparent Menu to colored Menu on scroll

I am definitely a beginner at js,I would like a Transparent Menu and when scrolling down a smooth transition happens from transparent to white with a box shadow. but the code js doesn't work

<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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • Place the x definition inside the see function
  • Place window.addEventListener("onscroll",see); after! (outside) the see function
  • Use the "scroll" Event name
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

Also, styling should go into CSS, not dispersed around your JS files.
Use Element.classList.toggle() to toggle a predefined CSS class:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...