[英]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.