嘿,我有4个图标和
元素。 我想为图标添加事件监听器,所以当我将它们悬停时,我会看到p元素并隐藏图标。
我可以这样:
document.getElementById('burger').addEventListener('mouseenter', function(){
document.getElementById('burgerP').style.display = 'block';
document.getElementById('burger').style.display = 'none';
})
document.getElementById('burgerP').addEventListener('mouseleave', function(){
document.getElementById('burgerP').style.display = 'none';
document.getElementById('burger').style.display = 'block';
})
document.getElementById('food').addEventListener('mouseenter', function(){
document.getElementById('foodP').style.display = 'block';
document.getElementById('food').style.display = 'none';
})
document.getElementById('foodP').addEventListener('mouseleave', function(){
document.getElementById('foodP').style.display = 'none';
document.getElementById('food').style.display = 'block';
})
document.getElementById('location').addEventListener('mouseenter', function(){
document.getElementById('locationP').style.display = 'block';
document.getElementById('location').style.display = 'none';
})
document.getElementById('locationP').addEventListener('mouseleave', function(){
document.getElementById('locationP').style.display = 'none';
document.getElementById('location').style.display = 'block';
})
document.getElementById('delivery').addEventListener('mouseenter', function(){
document.getElementById('deliveryP').style.display = 'block';
document.getElementById('delivery').style.display = 'none';
})
document.getElementById('deliveryP').addEventListener('mouseleave', function(){
document.getElementById('deliveryP').style.display = 'none';
document.getElementById('delivery').style.display = 'block';
})
但是我想使其简单并使其在forEach循环中。但是当我做到这一点时,我只会在第一个
元素上生效。我应该创建一个节点列表吗? 如果是这样,那又如何? (请不要让我的代码告诉我该怎么做,我想学习它而不是复制/粘贴)
我试图使它像这样:
document.querySelectorAll('.ikonka').forEach((icon) => {
icon.addEventListener('mouseenter', () => {
document.querySelector('.ikonka').style.display = "none";
document.querySelector('.opis').style.display = "block";
});
icon.addEventListener('mouseleave', () =>{
document.querySelector(".opis").style.display = "none";
document.querySelector(".ikonka").style.display = "block";
})
}
)
此处和HTML代码:
<section id="category">
<div class="burgers">
<i class="fas fa-hamburger ikonka" id="burger"></i>
<p id="burgerP" class="opis">Our burger's!</p>
</div>
<div class="mainFood">
<i class="fas fa-utensils ikonka" id="food"></i>
<p id="foodP" class="opis">Best dishes</p>
</div>
<div class="location">
<i class="fas fa-map-marked-alt ikonka" id="location"></i>
<p id="locationP" class="opis">We are here!</p>
</div>
<div class="delivery">
<i class="fas fa-car ikonka" id="delivery"></i>
<p id="deliveryP" class="opis">Free Delivery!</p>
</div>
<script src="app.js"></script>
</section>
答案 0 :(得分:0)
您可以设置一个包含元素ID(位置,交货等)的全局数组。 然后,使用for循环遍历此数组,并将样式添加到内部引用的每个元素中。