我需要在導航欄上設定三個不同的背景:
1.如果頁面滾動小于400 px,則沒有背景
2.如果頁面滾動超過 400 像素,則兩種不同的顏色: a)向下滾動時為藍色 b)向上滾動時為綠色。
我嘗試使用以下代碼,但似乎在我輸入第一個 IF 后,即使頁面小于 400 像素,該功能也會繼續作業。
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("nav1").style.background = "rgba(0, 41, 51,1)";
} else {
lastScroll = currentScroll;
document.getElementById("nav1").style.background = "rgba(68,78,36,1)";
}
prevScrollpos = currentScrollPos;
} else {
document.getElementById("nav1").style.background = "rgba(0,0,0,0)";
}
}
謝謝!
uj5u.com熱心網友回復:
不要嘗試將兩個函式分配給window.onscroll,它是一個屬性并且只能包含一個函式。
這是您當前代碼的情況:
- 一個匿名函式被宣告(它呼叫
scrollFunction)并分配給window.onscroll - 在第一卷,
scrollFunction被稱為。如果頁面尚未滾動超過 400 像素,if則不會執行該塊。 - 一旦頁面超過 400 像素,
prevScrollpos就會被宣告...然后之前分配給的函式將window.onscroll被新的函式覆寫。
這就是為什么之后沒有進行 400px 比較的原因。它超出了第二個功能。第一個迷失在虛無之中。
這是您想要實作的目標:
// This variable needs to be global
let prevScrollpos = 0;
// This getElement can also be global
let nav1 = document.getElementById("nav1")
function scrollFunction() {
// This varable needs to be local
let currentScrollPos = window.pageYOffset;
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
// Determine scroll direction
if (prevScrollpos > currentScrollPos) {
nav1.style.background = "rgba(0, 41, 51,1)";
} else {
nav1.style.background = "rgba(68,78,36,1)";
}
}
// If below 400px
else {
nav1.style.background = "rgba(0,0,0,0)";
}
// Update this variable for the next iteration
prevScrollpos = currentScrollPos;
// For this demo only
console.clear()
console.log(currentScrollPos)
}
// Assign the scrollFunction reference to the window property
window.onscroll = scrollFunction;
body {
height: 1000px;
}
#nav1{
position: sticky;
top: 4px;
height: 100px;
border: 1px solid black;
}
<div id="nav1"></div>
uj5u.com熱心網友回復:
您可以使用此腳本:
<script>
window.onscroll = function () { myFunction() };
function myFunction() {
if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
var lastScrollTop = 0;
window.addEventListener("scroll", function () {
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop) {
document.getElementById("nav").style.background = "rgba(0, 41, 51,1)";
} else {
document.getElementById("nav").style.background = "rgba(68,78,36,1)";
}
lastScrollTop = st <= 0 ? 0 : st;
}, false);
} else {
document.getElementById("nav").style.background = "rgba(0,0,0,0)";
}
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/411890.html
標籤:
下一篇:如何使用CSS進行下拉選單轉換?
