如何构建包含条件的数组

我需要构建一个窗口侦听器,该侦听器mouseover在使用的盒子上触发,但contains我不太确定如何构建它?


这是我建立的一个测试:


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

  }


}


倚天杖
浏览 144回答 3
3回答

慕村9548890

看看以下是否适合你。function trial(e) {&nbsp; const contain_material = document.getElementsByClassName("item")&nbsp; for (var i = 0; i < contain_material.length; i++) {&nbsp; &nbsp; if(contain_material[i] == e.target) {&nbsp; &nbsp; &nbsp; alert("so far so good")&nbsp; &nbsp; }&nbsp; }}

繁星点点滴滴

你不能只听鼠标悬停在框元素上而不是整个页面上吗?function handleMouseOver() {&nbsp; alert('so far so good')}// or you can add dynamicaly with jsvar boxes = document.getElementsByClassName("item");Array.from(boxes).forEach(function() {&nbsp; 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 HTMLCollectionbody {&nbsp; display: flex;}.item {&nbsp; width: 300px;&nbsp; height: 300px;&nbsp; background-color: yellow;&nbsp; margin: 10px;}<!DOCTYPE html><html><head>&nbsp; <meta charset="UTF-8">&nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; <meta http-equiv="X-UA-Compatible" content="ie=edge">&nbsp; <title>Document</title></head><body>&nbsp; <div class="item" onmouseover="handleMouseOver()"></div>&nbsp; <div class="item" onmouseover="handleMouseOver()"></div>&nbsp; <div class="item" onmouseover="handleMouseOver()"></div>&nbsp; <div class="item" onmouseover="handleMouseOver()"></div></body></html>

三国纷争

与其检查窗口上的悬停,为什么不检查这些元素之一何时悬停在上面。例如:const contain_material = document.getElementsByClassName("item")for (mat of contain_material) {&nbsp; mat.addEventListener("mouseover", trial)}function trial(e) {&nbsp; alert("so far so good")&nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript