带有 Javascript 的鼠标悬停和鼠标移开

新手上路,请多包涵

我正在尝试调用 mouseover 和 mouseout 的函数。我尝试了在这里找到的各种不同的解决方案,但没有成功。

这就是我所在的位置。请解释解决方案,因为我有兴趣了解问题,而不仅仅是寻找快速解决方案。

 function MouseOver(elem) {
document.getElementsByName(elem).style.color("white");
}

function MouseOut(elem) {
document.getElementsByName(elem).style.color("black");
}

<nav id="frame-link">
<a href="index.html" name="home" onmouseover="MouseOver(this);" onmouseout="MouseOut(this);">Home</a>
</nav>

原文由 Tommy.Collins 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 308
2 个回答

当您调用内联事件处理程序时,例如使用 onmouseover="MouseOver(this);" 您正在将对元素本身的引用传递给您的函数,并且在您的函数中,您正在获取该引用并将其分配给变量 elem

然后,您通常会在函数中使用 elem ,例如 elem.style.color = "white"; ,而不是带括号,因为您没有运行函数,而只是更改属性。

 function MouseOver(elem) {
  elem.style.color = "white";
}

function MouseOut(elem) {
  elem.style.color = "black";
}
 <nav id="frame-link">
  <a href="index.html" name="home" onmouseover="MouseOver(this);" onmouseout="MouseOut(this);">Home</a>
</nav>

原文由 j08691 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果真的只是样式需要更改,那么您根本不需要 JavaScript。您可以将 CSS 与 :hover 伪类一起使用:

 .normal { background-color:#e0e0e0; }
.normal:hover { background-color:yellow; }
 <nav id="frame-link">
<a href="index.html" name="home" class="normal">Home</a>
</nav>

但是,如果它不仅仅是样式,那么您将希望以现代的、基于标准的方式来实现。不要使用内联 HTML 事件处理属性(请参阅 此处 了解原因)。这种语法需要更多的输入,但它带来的所有好处都是值得的。

最后,(再一次),如果您追求的是样式,那么使用类比使用单个样式属性要简单得多。

 // Get a reference to the element that needs to be worked with
var theLink = document.querySelector("a[name='home']");

// "Wire" the element's events
theLink.addEventListener("mouseover", mouseOver);
theLink.addEventListener("mouseout", mouseOut);

function mouseOver() {
  theLink.classList.add("hovered");
}

function mouseOut() {
  theLink.classList.remove("hovered");
}
 .normal { background-color: #e0e0e0; }
.hovered { background-color: yellow; }
 <nav id="frame-link">
  <a href="index.html" name="home" class="normal">Home</a>
</nav>

原文由 Scott Marcus 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏