简体   繁体   English

vanilla javascript 动画仅适用于一个元素?

[英]vanilla javascript animation only working for one element?

I wrote an animation to fade a list item off of the page, but it is only working for the first class that has the class name .grid-item, why is this happening and how can I fix this problem?我编写了一个动画来淡出页面上的列表项,但它仅适用于具有类名 .grid-item 的第一个类,为什么会发生这种情况,我该如何解决这个问题? It works perfectly fine for the first grid item and then nothing for the others.它对第一个网格项目非常好,然后对其他网格项目没有任何效果。

 let addCart = document.querySelector(".add-btn"); let item = document.querySelector(".grid-item"); addCart.addEventListener("click", function() { item.style.animation = "add-cart"; item.style.animationDuration = "3s"; setTimeout(() => { item.style.animation = "none"; }, 1000); });
 @keyframes add-cart { 0% { transform: translateY(0px); z-index: 1000; } 50% { transform: translateY(210%) scale(0.3); opacity: 0.1; } 51% { transform: translateY(-110%); } 100% { transform: translateY(0px); } } .animation { animation: add-cart; animation-duration: 3s; }
 <div class="grid-item"> <h3 class="title">Cano One</h3> <div class="img-container"> <img class="bike-image" src="img/bike1.png" alt="bike" /> </div> <p class="item-price">$2850</p> <button class="add-btn"><p class="plus">+</p></button> </div> <div class="grid-item"> <h3 class="title">Predator</h3> <div class="img-container"> <img class="bike-image" src="img/bike2.png" alt="bike" /> </div> <p class="item-price">$2010</p> <button class="add-btn"><p class="plus">+</p></button> </div>

You need to use querySelectorAll so the click event listener can be added to all the elemlents.您需要使用querySelectorAll以便将click事件侦听器添加到所有元素。

let gridItems = document.querySelectorAll(".grid-item");
gridItems.forEach(item => {
  const button = item.querySelector('.add-btn')
  button.addEventListener('click', () => {
    item.style.animation = "add-cart";
    item.style.animationDuration = "3s";

    setTimeout(() => {
      item.style.animation = "none";
    }, 1000);
  })
})

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

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