window.addEventListener('load',function () {
    var btnMoveL = document.querySelector('.left');
    var btnMoveR = document.querySelector('.right');
    var home = document.querySelector('.home');
    var imgW = home.offsetWidth;
    home.addEventListener('mouseover',function () {
        btnMoveL.style.display = 'block';
        btnMoveR.style.display = 'block';
    });
    home.addEventListener('mouseout',function () {
        btnMoveL.style.display = 'none';
        btnMoveR.style.display = 'none';
    });
    var ul = home.querySelector('ul');
    var list = home.querySelector('.list');
    //动态创建左下角按钮
    for (var i = 0 ; i<ul.children.length ; i++){
        var li = document.createElement('li');
        //为生成的li绑定索引号
        li.setAttribute('index',i);
        list.appendChild(li);
        //在生成li时直接绑定点击事件
        li.addEventListener('click',function () {
            //干掉所有人
            for (var i = 0;i<list.children.length;i++){
                console.log(list.children[i]);
                list.children[i].className = '';
            }
            this.className = 'current';

            //点击按钮移动图片 移动的距离等于 索引号 * 图片的宽度
            var index = this.getAttribute('index');
            //当我们点击小圆点 箭头的值不会改变我们需要将 index的值赋值给num
            num = index;
            //小圆点的滚动同理
            scc = index;
            //因为需要往左走 所以值应该为负数
            move(ul,-index * imgW)
        })
    }
    list.children[0].className = 'current';
    //克隆第一张图片到最后
    var first = ul.children[0].cloneNode(true);
    ul.appendChild(first);
    //实现右侧按钮点击
    var num = 0;
    var scc = 0;
    btnMoveR.addEventListener('click',function () {
        //当图片到最后一张照片时 将ul.left值设置为0
        if (num === 3){
            ul.style.left = 0+'px';
            num = 0;
        }
        num++;
        move(ul,-num * imgW);
        //小按钮跟随图片滚动而变化
        scc++;
        for (var i = 0;i<list.children.length;i++){
            list.children[i].className = '';
        }
        if (scc == list.children.length){
            scc=0;
        }
        list.children[scc].className = 'current';
    });
    btnMoveL.addEventListener('click',function () {
        //当图片到最后一张照片时 将ul.left值设置为0
        if (num == 0){
            num = ul.children.length -1 ;
            ul.style.left = -num * imgW +'px';
        }
        num--;
        move(ul,-num * imgW);
        //小按钮跟随图片滚动而变化
        scc--;
        if (scc<0){
            scc=list.children.length-1;
        }
        for (var i = 0;i<list.children.length;i++){
            list.children[i].className = '';
        }
        list.children[scc].className = 'current';
    })
})
Last modification:February 16th, 2020 at 10:30 pm