An infinite carousel with vanilla JavaScript

試著忘記壹切 提交于 2019-12-03 00:35:54

I created a simple slider with css transformations as the animation technique and plain Javascript.

var img = document.getElementsByClassName("img")[0]; 
img.style.transform = 'translate('+value+'px)';

You can test it in this codepen snippet. http://codepen.io/TobiObeck/pen/QKpaBr

A press on a button translates all images in the respective direction along the x-axis. An image on the edge, is set transparent outerImg.style.opacity = '0'; and translated to the other side. You can add or remove image elements in HTML and it still works.

In this second codepen snippet you can see how it works. The opacity is set to 0.5 so it is observable which image switches the side. Because overflow: hidden is removed, you can see how the images on the edge enqueue on the other side. http://codepen.io/TobiObeck/pen/WGpdLE

Moreover it is notworthy that it is checked wether the animation is complete, otherwise the simultaneously added translations would look odd. Therefore a click won't trigger another animation until unless the animation is completed.

img.addEventListener("transitionend", transitionCompleted, true);

var transitionCompleted = function(){
    translationComplete = true;
}

leftBtnCLicked(){
    if(translationComplete === true){
       //doAnimation
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!