After a period of time, B station will add a dynamic banner map on the home page. After the mouse is put on the left and right, each element in the banner map (characters/items) will move along with it, which is highly interactive and attractive. Today, a simple analysis of how to achieve it.

Winning dynamic banner

After reviewing the elements, you can see that the HTML structure for the banner area looks like this:

<div class='animated-banner'>
  <div class='layer'>
    <img src='0.png' />
  </div>
  <div class='layer'>
    <img src='1.png' />
  </div>
  <div class='layer'>
    <img src='2.png' />
  </div>
  <div class='layer'>
    <img src='3.png' />
  </div>.</div>    
Copy the code

Div. Layer style sheet:

.animated-banner>.layer {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    -ms-flex-pack: center;
    justify-content: center;
}
Copy the code

As can be seen from the above code, to achieve such a banner, first split a dynamic image into multiple layers, respectively saved as 0-n.png, each layer has only a part of the elements, for example:

  • PNG contains only the background image
  • 1. PNG only contains volleyball photos, the rest is transparent
  • 2. PNG only contains odd-numbered athlete photos, and the rest is transparent
  • 3. PNG only contains photos of athletes with even numbers, and the rest is transparent

The position attribute of the. Layer class is absolute, and both left and top are 0. After loading in sequence, the 4 PNG images from 0 to 3 are superimposed into a complete image, but it is only a static banner

Of course, if you just want to achieve a static banner, there is no need to split the image, just load an image.

Then move the mouse over the banner, and you can see that each layer (except for the background) is moving with the mouse, but the sliding distance is different:

As you can see, the value of the TRasForm attribute on the HTML element, which is the style of the IMG element in each Layer div, changes as the mouse moves left and right, so that the previously static image moves with the mouse.

You can also see that the transform property value of the IMG element style changes at different rates for each layer, which makes the distance of the image movement different for each layer, making the animation more realistic.

The specific implementation method should be to bind mousemove event to div element of. Layer, and dynamically modify the transform attribute value of each layer image according to the distance and direction of mouse movement.