根据类名而不是ID获取元素



我试图通过其类名而不是ID来选择元素,因为我有几个具有相同类名的元素,我试图在'mouseenter'和'mouseleave'上实现相同的效果。

这是我到目前为止的代码:

var circle = document.getElementById('circle')
var timer
circle.addEventListener('mouseenter', function () {
circle.classList.add('up')
timer = setInterval(function () {
circle.classList.toggle('up')
}, 1000)
})
circle.addEventListener('mouseleave', function () {
clearInterval(timer)
circle.classList.remove('up')
})
body {
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
}
div {
width: 50px;
height: 50px;
background-color: blue;
transition: transform 1s ease;
border-radius: 50px;
}
div.up {
transform: translateY(-20px);
}
<div id='circle'></div>

比如说,我想有多个盒子,我想设置一个单一的类"circle"对于它们中的每一个,而不是为每个创建一个唯一的ID,如,circle1, circle2,等等然后找到所有这些ID,我如何通过类名获取元素并应用与现在相同的效果呢?

var boxes = document.getElementsByClassName('box')
for (var i = 0; i < boxes.length; i++) {
boxes[i].addEventListener('click', myFunction);
}

上面的代码选择了类名为box的框,它返回一个NodeList,我们可以遍历节点列表并向每个节点添加EventListener。

在Google中一个搜索javascript元素按类:tuto如果你有一个类要搜索

document.getElementsByClassName('test')

如果你有2

document.getElementsByClassName('rouge test')

最新更新