前言:无论什么样式的轮播图,核心 JS 实现原理都差不多。所以小伙伴们,还是需要了解一下核心 JS 实验原理的。
效果图:
实现代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .carousel { display: flex; position: relative; width: 705px; margin: 50px auto; overflow: hidden; } .carousel-box { perspective: 1000px; width: 100%; height: 200px; } .carousel-item { position: absolute; left: calc(50% - 200px); width: 400px; height: 100%; user-select: none; transition: all 0.4s ease; } .indicator { position: absolute; top: calc(50% - 25px); width: 50px; height: 50px; line-height: 50px; text-align: center; border: 1px solid; z-index: 999; border-radius: 50%; font-size: 25px; cursor: pointer; } .prev { left: 0; } .next { right: 0; } </style> </head> <body> <div class="carousel"> <div class="carousel-box"> <img class="carousel-item" src="2.jpg" /> <img class="carousel-item" src="2.jpg" /> <img class="carousel-item" src="2.jpg" /> <img class="carousel-item" src="2.jpg" /> <img class="carousel-item" src="2.jpg" /> </div> <div class="indicator prev"><</div> <div class="indicator next">></div> </div> <script> const items = document.querySelectorAll(".carousel-item"); // 拿到所有轮播图片 let index = 2; // 当前索引 // 布局函数 const layout = () => { console.log(items, index); const offsetStep = 100; // 两张图片的偏移量 const scaleStep = 0.6; // 两张图片的缩放比例 const opacityStep = 0.5; // 两张图片的透明度 for (let i = 0; i < items.length; i++) { const item = items[i]; const dis = Math.abs(i - index); // 布局比例 const sign = i - index > 0 ? 1 : -1; // 布局方向 const zIndex = items.length - dis; const scale = scaleStep ** dis; let rotateY = 45 * -sign; const opacity = opacityStep ** dis; let xOffset = (i - index) * offsetStep; if (i !== index) { xOffset = xOffset + 100 * sign; } else { rotateY = 0; } item.style.zIndex = zIndex; item.style.transform = `translateX(${xOffset}px) scale(${scale}) rotateY(${rotateY}deg)`; item.style.opacity = opacity; console.log(item); } }; layout(); // 向前的按钮 const prev = document.querySelector(".prev"); prev.onclick = () => { index--; if (index < 0) { index = 0; } layout(); }; // 向后的按钮 const next = document.querySelector(".next"); next.onclick = () => { index++; if (index > items.length - 1) { index = items.length - 1; } layout(); }; // 点轮播图 items.forEach((item, i) => { item.onclick = () => { index = i; layout(); }; }); </script> </body> </html>