js 无缝轮播/原型方法封装

无缝轮播

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图</title>
    <style>
        *{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .flex{
            display: flex;
        }
        .com{   
            width: 400px;
            height: 200px;
            margin: 100px auto;
            position: relative;
            border: 1px solid black;
            overflow: hidden;
        }
        .sliderPage{
            height: 100%;
            position: absolute;
            top: 0;
            left: -400px;
            transition: all .3s;
        }
        .sliderPage li,
        .sliderPage img{
            width: 400px;
            height: 100%;
        }
        .cut{
            position: absolute;
            top: 50%;
            left: 0;
            height: 0;
            width: 100%;
            justify-content: space-between;
        }
        .cut div{
            height: 40px;
            width: 30px;
            line-height: 40px;
            text-align: center;
            margin-top: -20px;
            color: white;
            background-color: rgba(0, 0, 0, .4);
            cursor: pointer;
        }
        .dots{
            position: absolute;
            bottom: 10px;
            left: 0;
            width: 100%;
            justify-content: center;
        }
        .dots li{
            width: 10px;
            height: 10px;
            margin: 0 5px;
            border-radius: 50%;
            background-color: gray;
            cursor: pointer;
        }
        .dots li.dotsAct{
            background-color: aquamarine;
        }
    </style>
</head>
<body>
    <div class="com">
        <ul class="sliderPage flex">
            <!-- 最后一张图片 -->
            <li><img src="./img/cat4.jpg" alt=""></li>

            <!-- 真正的图片列表 -->
            <li><img src="./img/cat1.jpg" alt=""></li>
            <li><img src="./img/cat2.jpg" alt=""></li>
            <li><img src="./img/cat3.jpg" alt=""></li>
            <li><img src="./img/cat4.jpg" alt=""></li>

            <!-- 第一张图片 -->
            <li><img src="./img/cat1.jpg" alt=""></li>
        </ul>
        <div class="cut flex">
            <div class="prev"><</div>
            <div class="next">></div>
        </div>
        <ul class="dots flex">
            <li data-index='1' class="dotsAct"></li>
            <li data-index='2' class=""></li>
            <li data-index='3' class=""></li>
            <li data-index='4' class=""></li>
        </ul>
    </div>
    <script>
        let sliderPage = document.querySelector('.sliderPage')
            prev = document.querySelector('.prev')
            next = document.querySelector('.next')
            dots = document.querySelector('.dots')
            timer = null
            index = 1
            initdirection = 'right' // 初始方向
            direction = 'right' // 运动时方式
            isMove = true
            len = sliderPage.children.length - 1
            moveWidth = sliderPage.children[0].clientWidth 
        
        autoPlay()
        function autoPlay(){
            timer = setInterval(()=>{
                direction = initdirection
                direction === 'right' ? index++ : index--
                autoMove()
            }, 1000);
        }
        function autoMove(){
            isMove = false
            let move = index * moveWidth
            sliderPage.style.transition = 'all .3s'
            sliderPage.style.left = -move + 'px'
            dotsHandle(index)
        }
        
        function dotsHandle(i){
            let ls = i-1
            let dlen = dots.children.length - 1
            ls = ls < 0 ? dlen : ls
            ls = ls > dlen ? 0 : ls
            Object.values(dots.children).forEach((el, index) => {
                el.classList.remove('dotsAct')
                if(ls === index){
                    el.classList.add('dotsAct')
                }
            });
        }
       
        sliderPage.addEventListener('transitionend',function(){
            console.log(index)
            if(index >= len && direction == 'right'){ // 最后一张 方向 向后
                sliderPage.style.transition = 'none'
                sliderPage.style.left = -moveWidth+'px' // 最后一张就切换到第一张
                index = 1
            }
            if(index <= 0 && direction == 'left'){ // 向前移动 到第一张 向前
                sliderPage.style.transition = 'none'
                sliderPage.style.left = -moveWidth*(len-1) +'px' 
                index = len-1
            }
            isMove = true
        })

        dots.onclick = function(e){
            let target = e.target
            if(target.nodeName == 'LI'){
                clearInterval(timer)
                index = target.dataset.index
                autoMove()
                autoPlay()
            }
        }

        prev.onclick = function(){
            if(!isMove) return
            clearInterval(timer)
            direction = 'left'
            index--
            autoMove()
            autoPlay()
        }
        next.onclick = function(){
            if(!isMove) return
            clearInterval(timer)
            direction = 'right'
            index++
            autoMove()
            autoPlay()
        }



    </script>
</body>
</html>

原型方法封装

<!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>
        * {
            padding: 0;
            margin: 0;
            list-style: none;
        }

        
        .flex {
            display: flex;
        }

        .div {
            width: 400px;
            height: 200px;
            margin: 100px auto;
            position: relative;
            border: 1px solid black;
            overflow: hidden;
        }

        .sliderPage {
            height: 100%;
            position: absolute;
            top: 0;
            left: -400px;
            transition: all .3s;
        }

        .sliderPage li,
        .sliderPage img {
            width: 400px;
            height: 100%;
        }

        .cut {
            position: absolute;
            top: 50%;
            left: 0;
            height: 0;
            width: 100%;
            justify-content: space-between;
        }

        .cut div {
            height: 40px;
            width: 30px;
            line-height: 40px;
            text-align: center;
            margin-top: -20px;
            color: white;
            background-color: rgba(0, 0, 0, .4);
            cursor: pointer;
        }

        .dots {
            position: absolute;
            bottom: 10px;
            left: 0;
            width: 100%;
            justify-content: center;
        }

        .dots li {
            width: 10px;
            height: 10px;
            margin: 0 5px;
            border-radius: 50%;
            background-color: gray;
            cursor: pointer;
        }

        .dots li.dotsAct {
            background-color: aquamarine;
        }
    </style>
</head>

<body>
    <div class="div"></div>
    <script>
        HTMLDivElement.prototype.createTurnPage = function (option) {
            
            const {
                imgArr,
                isDots,
                isCut
            } = Object.assign({
                // 默认配置
                imgArr: [],
                isDots: true, // 是否需要小点
                isCut: true, // 是否需要左右切换
            }, option)
            const leng = imgArr.length

            // 创建图片容器
            const imgCon = creataEl('ul',['sliderPage','flex'])
            let lisArr = [imgArr[imgArr.length-1],...imgArr,imgArr[0]]
            lisArr.forEach(item=>{
                let li = creataEl('li')
                li.appendChild(creataEl('img',null,null,{src:item}))
                // creataEl('li').creataEl('img',null,null,{src:item}) li直接被img覆盖??
                imgCon.appendChild(li)
            })
            this.appendChild(imgCon)

            // 创建切换部分
            const cut = creataEl('div',['cut','flex'])
            const prev = creataEl('div',['prev'])
            const next = creataEl('div',['next'])
            prev.innerHTML = '<'
            next.innerHTML = '>'
            cut.appendChild(prev)
            cut.appendChild(next)
            if(isCut) this.appendChild(cut)

            // 创建点部分
            const dots = creataEl('ul',['dots','flex'])
            if(isDots){
                imgArr.forEach((s,i)=>{
                    let classList = []
                    if(i == 0) classList.push('dotsAct')
                    dots.appendChild(creataEl('li',classList,null,{'data-index':i+1}))
                })
                this.appendChild(dots)
            }
            
            // 轮播图运行
            turnPage(imgCon, prev, next, dots)
            function turnPage(sliderPage, prev, next, dots){
                let timer = null
                    index = 1
                    initdirection = 'right' // 初始方向
                    direction = 'right' // 运动时方式
                    isMove = true
                    len = sliderPage.children.length - 1
                    moveWidth = sliderPage.children[0].clientWidth 
                   
                autoPlay()
                function autoPlay(){
                    timer = setInterval(()=>{
                        direction = initdirection
                        direction === 'right' ? index++ : index--
                        autoMove()
                    }, 1000);
                }
                function autoMove(){
                    isMove = false
                    let move = index * moveWidth
                    sliderPage.style.transition = 'all .3s'
                    sliderPage.style.left = -move + 'px'
                    dotsHandle(index)
                }
                
                function dotsHandle(i){
                    let ls = i-1
                    let dlen = dots.children.length - 1
                    ls = ls < 0 ? dlen : ls
                    ls = ls > dlen ? 0 : ls
                    Object.values(dots.children).forEach((el, index) => {
                        el.classList.remove('dotsAct')
                        if(ls === index){
                            el.classList.add('dotsAct')
                        }
                    });
                }
            
                sliderPage.addEventListener('transitionend',function(){
                    if(index >= len && direction == 'right'){ // 最后一张 方向 向后
                        sliderPage.style.transition = 'none'
                        sliderPage.style.left = -moveWidth+'px' // 最后一张就切换到第一张
                        index = 1
                    }
                    if(index <= 0 && direction == 'left'){ // 向前移动 到第一张 向前
                        sliderPage.style.transition = 'none'
                        sliderPage.style.left = -moveWidth*(len-1) +'px' 
                        index = len-1
                    }
                    isMove = true
                })
                dots.onclick = function(e){
                    let target = e.target
                    if(target.nodeName == 'LI'){
                        clearInterval(timer)
                        index = target.dataset.index
                        autoMove()
                        autoPlay()
                    }
                }
                prev.onclick = function(){
                    if(!isMove) return
                    clearInterval(timer)
                    direction = 'left'
                    index--
                    autoMove()
                    autoPlay()
                }
                next.onclick = function(){
                    if(!isMove) return
                    clearInterval(timer)
                    direction = 'right'
                    index++
                    autoMove()
                    autoPlay()
                }
            }

            /**
             * 创建dom
             * @param {String} nodeName 节点名称 
             * @param {Array} classList class列表
             * @param {Object} styleObj 样式对象
             * @param {Object} propObj 固有属性对象
             */
            function creataEl(nodeName, classList=[], styleObj={}, propObj={}){
                const node = document.createElement(nodeName)
                node.classList = classList ? classList.join(" ") : ''
                styleObj && Object.keys(styleObj).forEach(key => {
                    let rkey = kaseSmallHump(key) // 处理 background-color
                    node.style[rkey] = styleObj[key]
                });
                propObj && Object.keys(propObj).forEach(key => {
                    if(key.indexOf('data-') != -1){ // 处理data-属性
                        let str = key.split('data-')[1]
                        let rstr = kaseSmallHump(str)
                        node.dataset[rstr]  = propObj[key]
                    }else{
                        node[key] = propObj[key]
                    }
                    
                })
                return node
            }

            // 短横杠兼容 -> 小驼峰
            function kaseSmallHump(str){
                return str.replace(/-\w/g,function($){
                    return $.split('')[1].toLocaleUpperCase()
                })
            }
        }

        const div = document.getElementsByClassName('div')[0]
        div.createTurnPage({
            imgArr: [
                "./img/cat1.jpg",
                "./img/cat2.jpg",
                "./img/cat3.jpg",
                "./img/cat4.jpg"
            ]
        })
    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值