Home>Article>Web Front-end> Native JS uses transform to achieve infinite scrolling effect of banner
First let’s talk about the principle.
This method can also ensure that the entire page always has only 2 img tags, without having to create all img nodes. The key point is to replace the src of the invisible img every time.
Animation implementation
This completes a moving animation.
1
2
3
4
var timeout = null; window.onload = function () { var oLeft = document.querySelector('.left'); var oRight = document.querySelector('.right'); var oButton = document.querySelector('.buttons'); var oButtons = document.querySelectorAll('.buttons p'); var oImgs = document.querySelectorAll('.box img'); var imgWidth = oImgs[0].width; var gIndex = 0; begainAnimate(); // 绑定左右点击事件 oLeft.onclick = function () { clearTimeout(timeout); leftMove(); begainAnimate(); }; oRight.onclick = function () { clearTimeout(timeout); rightMove(); begainAnimate(); }; // 绑定数字序号事件 oButton.onclick = function (event) { clearTimeout(timeout); var targetEl = event.target; var nextIndex = (+targetEl.innerText) - 1; console.log(nextIndex); rightMove(nextIndex); begainAnimate(); } // 默认初始动画朝右边 function begainAnimate() { clearTimeout(timeout); timeout = setTimeout(function () { rightMove(); begainAnimate(); }, 3000); } // 向左移动动画 function leftMove() { var nextIndex = (gIndex - 1 = oImgs.length) ? 0 : gIndex + 1; } animateSteps(nextIndex, 50); } // 一次动画 function animateSteps(nextIndex, timestamp) { var currentImg = oImgs[gIndex]; var nextImg = oImgs[nextIndex]; nextImg.style.zIndex = 10; var step = 0; requestAnimationFrame(goStep); // 走一帧的动画,移动timestamp function goStep() { var moveWidth = timestamp * step++; if (Math.abs(moveWidth) 0 ? (moveWidth - imgWidth) : (imgWidth + moveWidth)}px)`; requestAnimationFrame(goStep); } else { currentImg.style.zIndex = 1; currentImg.style.transform = `translate(0px)`; nextImg.style.transform = `translate(0px)`; oButtons[gIndex].setAttribute('class', ''); oButtons[nextIndex].setAttribute('class', 'active'); gIndex = nextIndex; } } } } window.onclose = function () { clearTimeout(timeout); }
Recommended tutorial: "js tutorial"
The above is the detailed content of Native JS uses transform to achieve infinite scrolling effect of banner. For more information, please follow other related articles on the PHP Chinese website!