您当前的位置: 首页 >  Java

命运之手

暂无认证

  • 4浏览

    0关注

    747博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Javascript】【UI】实现移动端轮播图

命运之手 发布时间:2019-05-28 17:47:18 ,浏览量:4

在这里插入图片描述 html代码



    
        
        
    

    
    
    

    

        

css代码


* {
    padding: 0px;
    margin: 0px;
}

#carousel_root {
    width: 100%;
    position: relative;
    overflow: hidden;
}

#carousel_image_pane {
    width: 500%;
    font-size: 0px;
    overflow: hidden;
}

#carousel_image_pane > img {
    width: 20%;
}

#carousel_point_pane {
    display: flex;
    position: absolute;
    bottom: 0px;
    left: 50%;
    transform: translate(-50%, -10px);
    font-size: 0px;
}

#carousel_point_pane > span {
    width: 20px;
    height: 20px;
    border-radius: 10px;
    background: white;
    display: inline-block;
    margin-left: 10px;
}

#carousel_point_pane > span.selected {
    background: orange;
}

js代码


$(() => {
    //查询元素
    let $carouselRoot = $("#carousel_root");
    let $carouselPane = $("#carousel_image_pane");
    let $carouselImgs = $("#carousel_image_pane>img");
    let $carouselDots = $("#carousel_point_pane>span");
    let imgWidth = $carouselImgs[0].width;

    //选中首个圆点
    $carouselDots[0].classList.add("selected");

    //记录滑动滑动位置和触摸位置
    let translateX = 0;
    let startTouchX;
    let currentTouchX;

    //触摸事件
    $carouselPane[0].addEventListener("touchstart", event => {
        startTouchX = event.touches[0].clientX;
        currentTouchX = startTouchX;
    });
    $carouselPane[0].addEventListener("touchmove", event => {
        translateX = translateX + (event.touches[0].clientX - currentTouchX) * 1.5;
        if (translateX > 0)
            translateX = 0;
        if (translateX < -4 * imgWidth)
            translateX = -4 * imgWidth;
        $carouselPane.css("transform", "translateX(" + translateX + "px)");
        currentTouchX = event.touches[0].clientX;
    });
    $carouselPane[0].addEventListener("touchend", event => {
        let index = -translateX / imgWidth;
        //滑动距离满三分之一自动滑动到下一张,不满自动取消
        if (currentTouchX < startTouchX)
            index = Math.floor(index + 0.5);
        if (currentTouchX > startTouchX)
            index = Math.ceil(index - 0.5);
        translateX = -index * imgWidth;
        $carouselPane.css("transform", "translateX(" + translateX + "px)");

        //选中对应圆点
        $carouselDots.removeClass("selected");
        $carouselDots[index].classList.add("selected");
    });

    //圆点点击事件
    $carouselDots.click(function () {
        let index = $(this).index();
        $carouselDots.removeClass("selected");
        $carouselDots[index].classList.add("selected");
        translateX = -index * imgWidth;
        $carouselPane.css("transform", "translateX(" + translateX + "px)");
    });
});

下一篇文章,我们对轮播图进行封装 将其封装成库,几行代码即可在任意页面中实现轮播图

关注
打赏
1654938663
查看更多评论
立即登录/注册

微信扫码登录

0.0882s