【问题标题】:How do I convert this code so the functions can take a variable?如何转换此代码以便函数可以使用变量?
【发布时间】:2022-02-12 13:38:01
【问题描述】:

当鼠标移过导航栏元素时,我正在尝试更改它们的颜色。

这段代码可以做到这一点,但只针对第一个按钮:

let navOne = document.getElementById("nav1");

function mouseOn() {
    nav1.style.color = "red";
}

function mouseOff() {
    nav1.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn);
navOne.addEventListener('mouseout', mouseOff);

我一直在尝试转换代码,以便这些功能适用于多个按钮,但似乎无法让它工作。到目前为止的代码如下:

let navOne = document.getElementById("nav1");

function mouseOn(navButton) {
    navButton.style.color = "red";
}

function mouseOff(navButton) {
    navButton.style.color = "black";
}

navOne.addEventListener('mouseover', mouseOn(navOne));
navOne.addEventListener('mouseout', mouseOff(navOne));

它没有错误,但当我将鼠标按钮移到 nav1 元素上时不会导致任何颜色变化。

非常感谢任何帮助。

【问题讨论】:

  • mouseOn(navOne) 立即调用该函数...在另一个注释中,函数内部的this 是触发事件的元素-因此,无需将示例navOne 传递为this === navOne里面mouseOn
  • 当然,你可以使用 CSS :hover 来实现这么简单的效果
  • 或者navOne.addEventListener('mouseover', () => mouseOn(navOne));

标签: javascript html css


【解决方案1】:

您可以让事件处理函数利用传入的event 参数:

function mouseOn(e) {
  e.target.style.color = "red";
}

function mouseOff(e) {
  e.target.style.color = "black";
}

for (let navItem of document.querySelectorAll('nav a')) {
  navItem.addEventListener('mouseover', mouseOn);
  navItem.addEventListener('mouseout', mouseOff);
}
nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}
<nav>
  <a href="#" id="nav1">Nav One</a>
  <a href="#" id="nav2">Nav Two</a>
</nav>

但是,现在使用 css :hover 伪属性将是首选方法。无需 JS 代码。

nav a {
  display: inline-block;
  padding: 10px;
  color: black;
}

nav a:hover {
  color: red;
}
<nav>
  <a href="#">Nav One</a>
  <a href="#">Nav Two</a>
</nav>

【讨论】:

  • 或使用this :p
  • @Bravo 是的,我不想在不必要的时候使用this,但这是一种选择。
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多