原生JavaScript封装一个轮播图

原生JavaScript写轮播图

这是对京东网页轮播图的仿写

HTML布局

<body>
    <div class="banner">
        // 往左翻页按钮
        <div id="left" class="iconfont icon-left">div>
        <ul>
            <li>
              <div>图片链接div>
            li>
            <li>
              <div>图片链接div>
            li>
            <li>
              <div>图片链接div>
            li>
            <li>
              <div>图片链接div>
            li>
        ul>
        // 下面显示某页的小圆点
        <ol>ol>
        // 往右翻页按钮
        <div id="right" class="iconfont icon-right">div>
    div>
body>

JavaScript

var banner = document.querySelector('.banner')
var left = document.querySelector('#left');
var right = document.querySelector('#right')

// 鼠标经过轮播图 
banner.addEventListener('mouseover', function () {
    // 左右按钮显示
    left.style.display = 'block';
    right.style.display = 'block';
    // 清除轮播图的自动播放
    clearInterval(timer);
    timer = null;
});

// 鼠标离开轮播图
banner.addEventListener('mouseleave', function () {
    // 左右按钮隐藏
    left.style.display = 'none';
    right.style.display = 'none';
    // 开启轮播图自动播放
    timer = setInterval(function () {
        // 调用点击事件
        right.click()
    }, 3000)
});

var ul = banner.querySelector('ul');
var ol = banner.querySelector('ol');

var bannerWidth = banner.offsetWidth;
for (var i = 0; i < ul.children.length; i++) {
    // 创建一个li
    var li = document.createElement('li');
    // 拿到当前索引值
    li.setAttribute('index', i)

    //把li插入ol中
    ol.appendChild(li);
    // 生成小圆圈同时绑定点击事件
    li.addEventListener('click', function () {
        for (var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        this.className = 'current'
        //拿到当前li的索引值
        var index = this.getAttribute('index');
        //当我们点击了某个li 就要把这个索引号给num
        num = circle = index
        //点击小圆圈,移动ul
        animate(ul, -bannerWidth * index)
    })
}

// 开始时改变第一个小圆点样式
ol.children[0].className = 'current'
// 克隆第一张图片(li)放到ul最后面
var first = ul.children[0].cloneNode(true);
ul.appendChild(first);
// 点击按钮,图片滚动
var num = 0;
var circle = 0;
// flag 节流阀
var flag = true;
// 点击右按钮,图片左滚一张
right.addEventListener('click', function () {
    if (flag) {
        flag = false;
        // 如果走到最后一张,ul 的left=0
        if (num == ul.children.length - 1) {
            ul.style.left = 0;
            num = 0;
        }
        num++;
        animate(ul, -num * bannerWidth, function () {
            flag = true;
        });
        // 点击右侧按钮, 小圆圈跟随一起变化,可以再声明一个变量控制小圆圈
        circle++;
        if (circle == ol.children.length) {
            circle = 0;
        }

        circleChange();
    }

})

// 点击左按钮,图片左滚一张
left.addEventListener('click', function () {
    if (flag) {
        flag=false;
        // 如果走到第一张,ul 的left=ol.children.length*bannerWidth
        if (num == 0) {
            num = ul.children.length - 1;
            ul.style.left = -num * bannerWidth + 'px';

        }
        num--;
        animate(ul, -num * bannerWidth,function(){
            flag = true;
        });
        // 点击右侧按钮, 小圆圈跟随一起变化,可以再声明一个变量控制小圆圈
        circle--;
        // if (circle < 0) {
        //     circle = ol.children.length-1;
        // }
        circle = (circle < 0 ? ol.children.length - 1 : circle);
        circleChange();
    }
})

//自动播放
var timer = setInterval(function () {
    //手动调用点击事件
    right.click()
}, 3000)

function circleChange() {

    //先清除其余小圆圈的current类名
    for (var i = 0; i < ol.children.length; i++) {
        ol.children[i].className = '';
    }
    ol.children[circle].className = 'current';
}

function animate(obj, target, callback) {
    clearInterval(obj.timer);

    obj.timer = setInterval(function () {
        var step = (target - obj.offsetLeft) / 10;
        step = (step > 0 ? Math.ceil(step) : Math.floor(step));
        if (obj.offsetLeft == target) {
            clearInterval(obj.timer);

            callback && callback();
        }
        obj.style.left = obj.offsetLeft + step + 'px'
    }, 17)
}


CSS

这里左右切换引入了Iconfont矢量图标库的图标!

@font-face {font-family: "iconfont";
    src: url('//at.alicdn.com/t/font_1650071_0h2k33iyxy3l.eot?t=1582275927844'); /* IE9 */
    src: url('//at.alicdn.com/t/font_1650071_0h2k33iyxy3l.eot?t=1582275927844#iefix') format('embedded-opentype'), /* IE6-IE8 */
    url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAALEAAsAAAAABsQAAAJ1AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDBgqBFIESATYCJAMMCwgABCAFhG0HTRvvBcgekiQlKiFECCROAQCmePhv+e6+mdlNa1W2KqMS6I4uPBoFUjTjczxVo///zmVuQA4hQ3XEakSKbeknTQ/Sl+bIjcCOhQIyGoXchCOhdrlax+vzXE5vAh3IXfUty2lNGnv6US/AOKBA98A2WQcUBsItdZNxVfToH+cJtJrk5rqYWVpFdQo0LRAfGFVRXSehKEm5Wagn1hbxRaU5fUrvkM9S+vgnGHUkVYbm3r6aNtDYTz+/5s3GpmeckCT4mytkrEMK8WKy8EilSLhKrdaq5fpaEdJZ6UYZqa3t9Uv/eImoodZ2sOwXEz9RJcHPN0ggg7pbmoNsBWz/o0P09DrG6fHdVjsl51v3JyNwtUm3uunFye1miwFnmzfHo+T65fHN3P9aA5tnkbmsJOqcnftbNfKx9W80SBFk0kMqy18Egr7RvT8vuw7+N7cV8ND3Dc9RwO3N7w8G/0sH7Cq1ATlzKbVU24ayXoAv4avTsAYU6fW13z4A7iQ0G9gRajJhkTWbJwu7jkqbfdSaHaPVmtnNbfoIlaK0YNWeh9DtGUmnH8i6fZCF/URl0Ddq3VGJVnfRt2ebxWAN5wJUCQbWSpjpPEuIWzao9mWgubQqXIPk10E4LI0DXn+/PAtZEGcscPI0KCXBRPAMnvEug3SaY1twC3TpNaW0kz4fmXqTV+cZ1OCcAFQSMGCaEozRcVmE95caBp9fBqicNJVYEK1U1wHBwYbHArz8AHLWmgWJvuUaRx4VJEkERghcBjbjjQJpaRxmT4+yAJ3kZe7I2ZJ8uBeBWr332zPfdwBaoe/lSJGj6HrH1KzkOVUIXgjHY43dehNUI4YQAAAA') format('woff2'),
    url('//at.alicdn.com/t/font_1650071_0h2k33iyxy3l.woff?t=1582275927844') format('woff'),
    url('//at.alicdn.com/t/font_1650071_0h2k33iyxy3l.ttf?t=1582275927844') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
    url('//at.alicdn.com/t/font_1650071_0h2k33iyxy3l.svg?t=1582275927844#iconfont') format('svg'); /* iOS 4.1- */
  }
.iconfont:hover{
    background-color: rgba(0,0,0,.4);
}

.icon-right,
.icon-left{
    z-index: 2;
    display:none;
    border-top-right-radius: 18px;
    border-bottom-right-radius: 18px;
    background-color: rgba(0,0,0,.15);
}
  .icon-right{
    right: 0;
    transform: rotate(180deg);
  }
  .icon-right:before {
    content: "\e6bc";
  }
  
  .icon-left:before {
    content: "\e6bc";
  }
  

*{
    margin: 0;
    padding: 0;
}

body{
  width: 100%;
  height: 100%;
}

.banner{
    width: 590px;
    height: 470px;
    overflow: hidden;
    position: relative;
}

ul{
    position: relative;
    height: 470px;
    width: 600%;
    list-style: none;
}

ul li{
    position: relative;
    float: left;
    width: 590px;
}

li div{
  display: flex;
  justify-content: center;
  margin: 220px;
  font-size: 30px;
  color: #f44336;
}

img{
    width: 590px;
}

ol{
    display: flex;
    position: absolute;
    bottom: 5%;
    left: 44%;
    list-style: none;
}

ol li{
    width: 9px;
    height: 9px;
    border-radius: 50%;
    border: 1px solid #fff;
    margin-right: 5px;
}

.current{
    background-color: #fff;
}

你可能感兴趣的:(原生JavaScript封装一个轮播图)