我尝试了很多这种代码的组合,但没有任何方法可以正常运行。我也尝试过scrollTop。只要查看我的js代码并告诉我它有什么问题。
<header>
<div class="nav" id="nav">
<div class="navRow" id="navRow">
<div class="navBrand" id="brand"><a href="#"><img src="img/logo-light.png" alt="Snow" height="35"></a></div>
<div class="navLinks">
<div class="navItem"><a href="#">About</a></div>
<div class="navItem"><a href="#">Contact</a></div>
<div class="navItem"><a href="#">Portfolio</a></div>
<div class="navItem"><a href="#">Blog</a></div>
<div class="navItem"><a href="#">Wordpress Theme</a></div>
</div>
</div>
</div>
</header>
<script>
var yPos = window.pageYOffset;
var nav = document.getElementById("nav");
if (yPos > 50 || document.body.pageYOffset > 50) {
nav.style.backgroundColor = "white";
}
else {
nav.style.backgroundColor = "none";
}
</script>
答案 0 :(得分:0)
您的代码只在页面加载时运行一次。我想你希望它能在每个滚动事件上运行:
window.addEventListener('scroll', function(e) {
// ... your code here
})