简体   繁体   中英

Render a div visible or hidden depend on mouseOver and mouseOut

I have these 9 cards, for each cards when the mouse is over the component I would hide/visible.

``
<div class="cards__food">
    <% @foods.each do |food| %>
      <%= link_to(foods_path) do %>
        <div class="card__food">
          <div class="card__food-img" style="background-image: url(<%= food.image_url %>);"></div>
          <h3><%= food.name.upcase %></h3>
          <div id="hide">
            <p>ORDER</p>
          </div>
        </div>
        <% end %>
      <% end %>
  </div>

#hide {
  visibility: hidden;
}
  • I selected each cards. Each have been assigned to a variable cards.
  • To have effect on i did the same things

Here is my trouble, without forEach i can't use addEventListener.

the console said:

TypeError: cards.addEventListener is not a function

So i used forEach. But when the mouse is over a card only the first card trigger and render visible or hide:

          <div id="hide">
            <p>ORDER</p>
          </div>

depend on mouseover/mouseout

const addOrderToFood = () => {
  const cards = document.querySelectorAll(".card__food");
  const order = document.getElementById('hide');
  if (cards) {
    cards.forEach(card => {
      card.addEventListener("mouseover", (event) => {
        console.log(event)
        order.style.visibility='visible';
      })
      card.addEventListener("mouseout", (event) => {
        console.log(event)
        order.style.visibility='hidden';
      })
    })

  }

}

I can't find a issue and I really want to beat this piece of code haha: :D

Plain CSS will do. hide selector should not be an id, because it is appearing multiple times on the page.

.card__food:hover > .hide {
    visibility: 'visible';
}
.card__food > .hide {
    visibility: 'hidden';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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