[英]How do I convert this code so the functions can take a variable?
I am trying to change the color of nav bar elements when the mouse goes over them.当鼠标经过它们时,我正在尝试更改导航栏元素的颜色。
This piece of code does that but for only the first button:这段代码可以做到这一点,但仅适用于第一个按钮:
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);
I have been trying to convert the code so the functions work for multiple buttons, but cannot seem to get it to work.我一直在尝试转换代码,以便这些功能适用于多个按钮,但似乎无法使其正常工作。 Here is the code so far:这是到目前为止的代码:
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));
It has no errors, but does not cause any color change when I move my mouse button over the nav1 element.它没有错误,但当我将鼠标按钮移到 nav1 元素上时不会导致任何颜色变化。
Any help is greatly appreciated.任何帮助是极大的赞赏。
You can have the event handler functions take advantage of the event
parameter that is passed in:您可以让事件处理函数利用传入的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>
However, using a css :hover
pseudo-attribute would be the preferred approach nowadays.但是,现在使用 css :hover
伪属性将是首选方法。 No JS code needed.无需 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.