简体   繁体   中英

How to use Element.animate() to animate an slider?

I'm trying to recreate a slider using JS and animate it without keyframes, using only method animate. And It worked but not as expected; I'm able to move elements from one side to another but it seems to be the same element. I'm wordering why. I couldn't find a solution or bug in my code. Could somebody give me a hand?

Here it is: https://codepen.io/lelre-ferreira/pen/oNGOaVj

<div class="container">
  <div class="slider">
    <div class="box">
      <div class="slide1">SLIDE 1</div>
      <div class="slide1">SLIDE 2</div>
      <div class="slide1">SLIDE 3</div>
    </div>
  </div>
  <div class="control">
    <div class="btn1">right</div>
    <div class="btn3">center</div>
    <div class="btn2">left</div>
  </div>
</div>

It seems to looping throught one item not the three of them;

const box = document.querySelector(".box");
const slide = document.querySelector(".slide1");

const leftControl = document.querySelector(".btn2");
const rightControl = document.querySelector(".btn1");
const centerControl = document.querySelector(".btn3");

moveLeft = () => {
  //box.style.transform = "translateX(-40rem)";
  box.animate(
    [{ transform: "translateX(40rem)" }],
    {
      duration: 1000
    }
  );
};
leftControl.addEventListener("click", moveLeft);

moveRight = () => {
  box.animate(
    [{ transform: "translateX(-40rem)" }],
    {
      duration: 1000
    }
  );
};
rightControl.addEventListener("click", moveRight);

moveCenter = () => {
  box.animate(
    [{ transform: "translateX(0)" }],
    {
      duration: 1000
    }
  );
};
centerControl.addEventListener("click", moveCenter);

//`translateX(${slideSize}px)`;

Why did you use const slide = document.querySelector(".slide1"); when you meant to select all slide1 elements? Use querySelectorAll instead. Also, you're not using slide1 in your code. This piece of code is not necessary.

You can solve your problem by adding fill: 'forwards' after the duration of the animation.

I found out its necessary to specify the fill-mode for an animation in some cases. It works like keyframes: none, forwards, backwards and both.

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