Function description and end result

Use the Flex layout to achieve a kind of accordion effect, where clicking on a block will magnify it and other areas will divide the rest.

style

There are already many tutorials on flex layout available online.

//dom structure body (display:flex) box-item (flexitem) top_text MID_text bottom_text box-item...Copy the code

The background image content is centered

background-size: cover;
background-position: center;
Copy the code

In the initial state, the text at the top and bottom is not displayed on the page. Translate is set to allow for transitions

.box-item p.top {
  transform: translateY(-120%);
}
.box-item p.bottom {
  transform: translateY(120%);
}
Copy the code

I also learned a selector that I didn’t use much before:

// Select all children of this element. Bot-item > *Copy the code

function

Bind click events

Listen for an event on the body

How do I find the clicked element

Add a custom parameter to all box-items and use event.target, but consider that there are children under box-items, so you need to check

 if (event.target.className.includes("box-item")) {
        index = event.target.getAttribute("data-index");
      } else {
        index = event.target.parentNode.getAttribute("data-index");
      }
Copy the code

Add and remove styles

There are several ways:

1. Get the className of the DOM, delimit it with a string method, and then do the array operation

2. Use dom. ClassList. Toggle

dom.classList.toggle("active");
Copy the code