繁体   English   中英

如何构建数组包含条件

[英]How to build array contains conditional

我需要构建一个 window 侦听器,该侦听器使用contains在框上触发mouseover ,我不太确定如何构建它?

是我建立的一个测试:

window.addEventListener("mouseover", trial)

function trial(e) {
  const contain_material = document.getElementsByClassName("item")
  if(contain_material.contains(e.target)) {
    alert("so far so good")
  }
  else {
    return
  }

}

看看以下内容是否适合您。

function trial(e) {
  const contain_material = document.getElementsByClassName("item")
  for (var i = 0; i < contain_material.length; i++) {
    if(contain_material[i] == e.target) {
      alert("so far so good")
    }
  }
}

与其检查 window 上的 hover,不如只检查其中一个元素何时悬停。 例如:

const contain_material = document.getElementsByClassName("item")
for (mat of contain_material) {
  mat.addEventListener("mouseover", trial)
}
function trial(e) {
  alert("so far so good")  
}

你不能只听盒子元素上的鼠标悬停而不是整个页面吗?

 function handleMouseOver() { alert('so far so good') } // or you can add dynamicaly with js var boxes = document.getElementsByClassName("item"); Array.from(boxes).forEach(function() { this.onmouseover = () => alert('so far so good') }) // () => this is an arrow function in case you dont know // Array.from() is because you can't use the forEach straight with a HTMLCollection
 body { display: flex; }.item { width: 300px; height: 300px; background-color: yellow; margin: 10px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="item" onmouseover="handleMouseOver()"></div> <div class="item" onmouseover="handleMouseOver()"></div> <div class="item" onmouseover="handleMouseOver()"></div> <div class="item" onmouseover="handleMouseOver()"></div> </body> </html>

暂无
暂无

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

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