无论事件监听器如何,函数都会触发

Functions fires regardless of the eventListeners

我试图在用户查看时更改该部分的背景,但是,当我添加事件列表时,它们无法正常工作。他们开火就好像没有事件监听器一样。非常感谢您的协助。

请在下面找到我的 JS 代码

const sections = document.querySelectorAll("section");

// this function changes the background of the section to show it is the active one
const activeSection = section => {
  section.style.backgroundColor = "#6BCAE2";
};

// this function return the section to its normal status when the user is not viewing it anymore
const inactiveSection = section => {
  section.style.backgroundColor = "";
};

// to loop throught the nodelist and add eventlistneres for the functions above
for (let section of sections) {
  section.addEventListener("mouseover", activeSection(section));
  section.addEventListener("mouseout", inactiveSection(section));
}

您需要使用匿名函数来传递您的参数:

for (let section of sections) {
  section.addEventListener("mouseover", () => { activeSection(section); });
  section.addEventListener("mouseout", () => { inactiveSection(section); });
}