带有香草JavaScript的无限旋转木马 [英] An infinite carousel with vanilla JavaScript

查看:113
本文介绍了带有香草JavaScript的无限旋转木马的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用纯JavaScript构建自己的 carousel

I am trying to build my own carousel with pure JavaScript.

我正在努力寻找最强高效方式来添加无限轮播选项。

I'm struggling with picking up the most efficient way to add an infinite carousel option.

由于某些原因,每个元素(照片,通用对象)必须具有 id

For some reasons, every element (photo, generic object) must have an id

我看到的算法是这样的:

The algorithm I see goes like that:


  • 检查轮播是否溢出(足够的物体足以满足整个容器的

  • 如果不是:将第一个元素的副本追加到后面,然后将第二个元素的
    a副本和等等。 (但是id会有问题,因为这个对象会有相同的id)


- 如果用户滚动到最后一个对象(右侧),则将
追加到数组的第一个DOM对象返回

- 如果用户滚动到
第一个对象(左边)然后将最后一个DOM子元素添加到数组
front。

- If the user is scrolling to the last object (to right) then append the first DOM object to the array back
- If the user is scrolling to the first object (to left) then add the last DOM child to array front.

这会起作用吗?有没有其他有效的方法来做一个无限的轮播?

我也听说过最好使用translate属性而不是改变左右属性因此,GPU的工作量会比CPU更多。

I have also heard that it's better to use translate property rather than changing the left, right properties, so it there would be more work for the GPU than for CPU.

推荐答案

我创建了一个带有css转换的简单滑块作为动画技术和普通的Javascript。

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)';

您可以在此codepen代码段中对其进行测试。
http://codepen.io/TobiObeck/pen/QKpaBr

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

按下按钮可沿x轴转换相应方向的所有图像。边缘上的图像设置为透明 outerImg.style.opacity ='0'; 并翻译到另一侧。您可以在HTML中添加或删除图像元素,但它仍然有效。

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.

在第二个代码笔代码段中,您可以看到它是如何工作的。 不透明度设置为 0.5 ,因此可以观察哪个图像切换侧面。由于删除了 overflow:hidden ,您可以看到边缘上的图像如何在另一侧排队。
http://codepen.io/TobiObeck/pen/WGpdLE

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
    }
}

这篇关于带有香草JavaScript的无限旋转木马的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆