繁体   English   中英

鼠标悬停和鼠标移开,带 Javascript

[英]Mouseover & Mouseout w/ 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>

当您调用内联事件处理程序时,例如使用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>

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

 .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>

这是您使用现代语法的非常简短的解决方案。

<a href="#" onmouseover="musOvr(this);" onmouseout="musOut(this);">Home</a>
<script>
  const musOvr = elem => elem.style.color = '#fff'
  const musOut = elem => elem.style.color = '#000'
</script>
  • 您需要将 JavaScript 代码放在<script>标签中。
  • elem不是名称,而是导致调用事件处理程序的 DOM 元素的实际引用。 看看javascript onclick 中的“this”是什么?
  • 以小写字母开头的函数名称是一种很好的风格。
  • 通过调用函数来应用属性的jQuery 不同,vanilla JavaScript elem.style.color是一个可写的字符串属性。 您需要分配一个值。

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

或者,使用onmouseover="mouseOver(event)"并编写:

function mouseOver(event) {
  var elem = event.target;
  elem.style.color = "white";
}

如果需要,这将允许您访问发生的event更多属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM