综合案例 --- 轮播图

1. 页面布局

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="container">
    <div class="carousel">
        <div>
            <a href="">
                <img src="./swiper-1.jpg">
            </a>
        </div>
        <div>
            <a href="">
                <img src="./swiper-2.jpg">
            </a>
        </div>
        <div>
            <a href="">
                <img src="./swiper-3.jpg">
            </a>
        </div>
    </div>

    <div class="indicators">
        <span class="active"></span>
        <span></span>
        <span></span>
    </div>
</div>

<script src="./index.js"></script>
</body>
</html>

index.css

.container {
    width: 500px;
    height: 300px;
    margin: 0 auto;
    position: relative;
    overflow: hidden;
}

.container .carousel{
    display: flex;
    transition: 0.5s;   /* 添加动画效果 */
}

.container .carousel div img {
    width: 500px;
    height: 300px;
}

.container .indicators {
    display: flex;
    margin-top: 200px;
    z-index: 100;
    position: absolute;
    bottom: 15px;

    /* 水平居中  start */
    left: 50%;
    transform: translateX(-50%);
    /* 水平居中  end */
}

.container .indicators span {
    width: 20px;
    height: 20px;
    background-color: #ccc;
    border-radius: 50%;
    margin-left: 10px;
}

.container .indicators span.active {
    background-color: #fff;
}

2. JS 交互

index.js

const doms = {
    carousel: document.querySelector('.container .carousel'),
    indicators: document.querySelector('.indicators'),
}

/**
 * @description 移动轮播图到第几张
 * @param {Number} index 板块的索引
 * */
function itemMoveTo(index) {
    // 方法一: 使用 margin-left 进行偏移
    // doms.carousel.style.marginLeft = "-" + index * 500 +  "px";

    // 方法二: 使用 transform 进行变换
    doms.carousel.style.transform = `translateX(-${index}00%)`;

    // 去除指示器之前的选中效果
    const activeEle = document.querySelector('.indicators span.active');
    activeEle.classList.remove('active');

    // 重新设置要选中的指示器选中效果
    doms.indicators.children[index].classList.add('active');
}

// 循环添加事件
for (let i = 0; i < doms.indicators.children.length; i++) {
    doms.indicators.children[i].addEventListener('click', () => {
        itemMoveTo(i)
    });
}
posted @ 2024-08-04 22:23  河图s  阅读(10)  评论(0)    收藏  举报