简体   繁体   English

检测我是否使用 vanilla javascript 悬停元素

[英]Detect if Im hovering an element using vanilla javascript

I need to detect if I'm hovering an element using only vanilla javascript.我需要检测我是否只使用 vanilla javascript 悬停一个元素。 I'm trying this:我正在尝试这个:

    this.element.addEventListener('mousemove', function () {

    var result = this.element.matches(':hover');

    if ( result ) {

      this.element.style.backgroundColor = "yellow";

    }

    console.log(result)

  }.bind( this )) 

But it isn't working as expected due it always console logs "false".但它没有按预期工作,因为它总是控制台记录“假”。

The use case is: A element have a class, and if I hover it, the class is removed and another class is added.用例是:一个元素有一个类,如果我将它悬停在它上面,该类将被删除并添加另一个类。

I know that jQuery has it's "hover" function but I need to accomplish that using only vanilla javascript.我知道 jQuery 有它的“悬停”功能,但我需要只使用 vanilla javascript 来完成它。

With vanilla JS, you can use the onmouseover tag.使用 vanilla JS,您可以使用 onmouseover 标签。

<div onmouseover="myFunc(this)">hover me!</div>
function myFunc(el) {
  console.log('hovering element',el);
}

Read more here: https://www.w3schools.com/jsref/event_onmouseover.asp在此处阅读更多信息: https : //www.w3schools.com/jsref/event_onmouseover.asp

However, if you have many elements that you want to programmatically add this to, then you can use a class selector in order to do so.但是,如果您想以编程方式将其添加到许多元素,那么您可以使用类选择器来执行此操作。

<div class="example">hover me!</div>
<div class="example">Also hover me!</div>
document.addEventListener("DOMContentLoaded", function(){
  // Handler when the DOM is fully loaded 
  var allMyHoverElements = document.getElementsByClassName("example");

  for (var i = 0; i < allMyHoverElements.length; i++) {
     allMyHoverElements.item(i).onmouseover = function() {
       console.log('Hello!');
     }
  }
});

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

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