有时导航栏的颜色在 Chrome 中没有变化

Sometimes the color of the navbar doesn't change in Chrome

我正在开发我的 web developer portfolio. In that when I press the hamburger, the color of the top nav bar should also change. But sometimes in Chrome it doesn't change and I have to reload. I thought it is probably because the script didn't load. But even after waiting for a long time this bug occurs. Can anyone say why it happens and how to solve it. Note that this color change is only for mobile nav. The source code is available at https://github.com/mrjithin/my-portfolio/。执行此操作的脚本在脚本文件夹中可用,名称为 ham.js。 顶部颜色应该与导航栏其余部分的颜色相同。

// ham.js
// For mobile hamburger
const mobNav = document.querySelector("nav#mobile");
const deskNav = document.querySelector("nav.desktop");
const navColor = window.getComputedStyle(mobNav).getPropertyValue("background-color");

document.getElementsByClassName("ham")[0].addEventListener("click", (event) => {
  document.getElementsByClassName("ham")[0].classList.toggle("cross");
  document.getElementById("line2").classList.toggle("none");
  mobNav.classList.toggle("on");
  mobNav.classList.toggle("off");
  if(mobNav.className === "on"){
    deskNav.style.backgroundColor = navColor;
  } else {
    deskNav.style.backgroundColor = "";
  }
  event.stopPropagation();
});

// To close the navbar on clicking a link. 
const mobileLis = document.querySelectorAll("nav#mobile a");

Array.from(mobileLis).forEach(link => {
  link.addEventListener("click", event => {
    document.getElementsByClassName("ham")[0].classList.toggle("cross");
  document.getElementById("line2").classList.toggle("none");
    mobNav.classList.toggle("on");
    mobNav.classList.toggle("off");
    if(mobNav.className === "on"){
      deskNav.style.backgroundColor = navColor;
    } else {
      deskNav.style.backgroundColor = "";
    }
    event.stopPropagation();
  })
})

提前致谢!

代替此代码

const navColor = window.getComputedStyle(mobNav).getPropertyValue("background-color");

试试这个

const navColor = () => window.getComputedStyle(mobNav).getPropertyValue("background-color");

并将navColor作为函数调用navColor()