Home  >  Article  >  Web Front-end  >  How to implement Touch carousel on mobile terminal using native js (code example)

How to implement Touch carousel on mobile terminal using native js (code example)

不言
不言forward
2019-01-07 09:46:162892browse

The content of this article is about the method (code example) of implementing the Touch carousel on the mobile terminal with native js. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.

Touch carousel

Touch carousel is actually to switch the carousel left and right by sliding your finger. Let’s use a case to show Implement it.

1. html structure

Structurally, ul and li are still used to store carousel images, and ol and li are used to store carousel dots:

How to implement Touch carousel on mobile terminal using native js (code example)

2. Style initialization

Some tags in html will have some default styles. For example, the body tag has a margin by default. In order not to affect the appearance, we Need to be cleared.
/* 清除标签默认边距 */
body,ul,li,ol,img {
    margin: 0;
    padding: 0;
}

/* 清除 ul 等标签前面的“小圆点” */
ul,li,ol {
    list-style-type: none;
}

/* 图片自适应 */
img {
    width: 100%;
    height: auto;
    border: none;
    /* ie8 */
    display: block;
    -ms-interpolation-mode: bicubic; /*为了照顾ie图片缩放失真*/
}

How to implement Touch carousel on mobile terminal using native js (code example)

3. Add style

When we talked about special effects earlier, we talked about how to use native js to move a wheel The concept of broadcasting pictures, but the method at that time was through li floating. Here I will introduce a new method to you - positioning.

Idea:

  • Give the outer box of ul a relative positioning;

  • The height of ul here cannot be Written to death, it should be the height of the li, but due to the absolute positioning of the li, there is no way to expand this height, so the height of the ul here needs to be dynamically set in js;

  • give Set the relative positioning of li, and both left and top are 0. Then add a transform:translateX(300%) attribute to li. The purpose is to initialize the displayed image to be empty, and then you only need to dynamically set the translateX value of each li in js. , you can achieve carousel;

  • Set the small dot area, because the number of small dots is unknown, so the width of ol is also unknown, and you want to center a box with an unknown width horizontally , can be achieved using absolute positioning combined with left percentage;

  • Set a width and height for the li below ol, add a rounded border attribute, and float it left, so that a row of empty spaces can be displayed The little dots of the heart;

  • Finally, add a style class and set a background attribute in it to display the small dots corresponding to the currently displayed image.

/* 轮播图最外层盒子 */
.carousel {
    position: relative;
    overflow: hidden;
}

.carousel ul {
    /* 这个高度需要在JS里面动态添加 */
}

.carousel ul li {
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    /* 使用 transform:translaX(300%) 暂时将 li 移动到屏幕外面去*/
    -webkit-transform: translateX(300%);
    transform: translateX(300%);
}

/* 小圆点盒子 */
.carousel .points {
    /* 未知宽度的盒子,使用 absolute 定位,结合 transform 的方式进行居中 */
    position: absolute;
    left: 50%;
    bottom: 10px;
    transform: translateX(-50%);
}

/* 小圆点 */
.carousel .points li {
    width: 5px;
    height: 5px;
    border-radius: 50%;
    border: 1px solid #fff;
    float: left;
    margin: 0 2px;
}

/* 选中小圆点的样式类 */
.carousel .points li.active {
    background-color: #fff;
}

How to implement Touch carousel on mobile terminal using native js (code example)

4. js preparation

  • Don’t think about anything else first , when js is initialized, the first thing to do is to add a height to ul, otherwise the picture will not be displayed.

  • Dynamicly set the height of UL

  • Dynamicly generate small dots (create the number of small dots based on the number of pictures, i=0 Add active)

  • Initialize the basic positions of the three li

Define three variables to store the bottom (left) of the three li's Store the subscript of the last picture, center and right store the subscripts of the first and second pictures respectively)

Set the left direction position of the three li after positioning through array [subscript]

var carousel = document.querySelector('.carousel');
var carouselUl = carousel.querySelector('ul');
var carouselLis = carouselUl.querySelectorAll('li');
var points = carousel.querySelector('ol');
// 屏幕的宽度(轮播图显示区域的宽度)
var screenWidth = document.documentElement.offsetWidth;

// 1- ul设置高度
carouselUl.style.height = carouselLis[0].offsetHeight + 'px';

// 2- 生成小圆点
for(var i = 0; i <p><span class="img-wrap"><img src="https://img.php.cn//upload/image/521/560/998/1546825265921477.jpg" title="1546825265921477.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>Rendering: </strong></p><p><span class="img-wrap"><img src="https://img.php.cn//upload/image/167/926/523/1546825280766035.jpg" title="1546825280766035.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>5. Add a timer to make the pictures move</strong></p>The carousel pictures will rotate by themselves, so you need to use a timer to execute the rotation function every once in a while. 
  • Add a timer and rotate the subscript in the timer

  • Extreme value judgment

  • Set transition (substitute The one does not require transition)

  • Return

  • Small dot focus linkage

var timer = null;
// 调用定时器
timer = setInterval(showNext, 2000);

// 轮播图片切换
function showNext(){
    // 轮转下标
    left = center;
    center = right;
    right++;
    // 极值判断
    if(right > carouselLis.length - 1){
        right = 0;
    }

    //添加过渡
    carouselLis[left].style.transition = 'transform 1s';
    carouselLis[center].style.transition = 'transform 1s';
    // 右边的图片永远是替补的,不能添加过渡
    carouselLis[right].style.transition = 'none';
    // 归位
    carouselLis[left].style.transform = 'translateX('+ (-screenWidth) +'px)';
    carouselLis[center].style.transform = 'translateX(0px)';
    carouselLis[right].style.transform = 'translateX('+ screenWidth +'px)';
    // 自动设置小圆点
    setPoint();
}

// 动态设置小圆点的active类
var pointsLis = points.querySelectorAll('li');
function setPoint(){
    for(var i = 0; i <p><span class="img-wrap"><img src="https://img.php.cn//upload/image/882/887/928/1546825314424596.jpg" title="1546825314424596.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>Rendering: </strong></p><p><span class="img-wrap"><img src="https://img.php.cn//upload/image/131/668/141/1546825350370455.gif" title="1546825350370455.gif" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p>##6 . touch sliding <strong></strong></p>
    The carousel image on the mobile terminal, combined with the touch sliding event, makes the effect more friendly.
  • Bind three touch events respectively

Record the finger position in touchstart, clear the timer, and record the time

Get it in touchmove Difference, clear transition at the same time, accumulate the value of the difference

touchend里面判断是否滑动成功,滑动的依据是滑动的距离(绝对值)

  • 超过屏幕的三分之一或者滑动的时间小于300毫秒同时距离大于30(防止点击就跑)的时候都认为是滑动成功

  • 在滑动成功的条件分支里面在判断滑动的方向,根据方向选择调用上一张还是下一张的逻辑

  • 在滑动失败的条件分支里面添加上过渡,重新进行归位

重启定时器

var carousel = document.querySelector('.carousel');
var carouselUl = carousel.querySelector('ul');
var carouselLis = carouselUl.querySelectorAll('li');
var points = carousel.querySelector('ol');
// 屏幕的宽度
var screenWidth = document.documentElement.offsetWidth;
var timer = null;

// 设置 ul 的高度
carouselUl.style.height = carouselLis[0].offsetHeight + 'px';

// 动态生成小圆点
for (var i = 0; i  carouselLis.length - 1) {
        right = 0;
    }
    //添加过渡(多次使用,封装成函数)
    setTransition(1, 1, 0);
    // 归位
    setTransform();
    // 自动设置小圆点
    setPoint();
}

// 轮播图片切换上一张
function showPrev() {
    // 轮转下标
    right = center;
    center = left;
    left--;
    // 极值判断
    if (left  screenWidth / 3 || (dTime  30)) {
        // 滑动成功了
        // 判断用户是往哪个方向滑
        if (dx > 0) {
            // 往右滑 看到上一张
            showPrev();
        } else {
            // 往左滑 看到下一张
            showNext();
        }
    } else {
        // 添加上过渡
        setTransition(1, 1, 1);
        // 滑动失败了
        setTransform();
    }

    // 重新启动定时器
    clearInterval(timer);
    // 调用定时器
    timer = setInterval(showNext, 2000);
}
// 设置过渡
function setTransition(a, b, c) {
    if (a) {
        carouselLis[left].style.transition = 'transform 1s';
    } else {
        carouselLis[left].style.transition = 'none';
    }
    if (b) {
        carouselLis[center].style.transition = 'transform 1s';
    } else {
        carouselLis[center].style.transition = 'none';
    }
    if (c) {
        carouselLis[right].style.transition = 'transform 1s';
    } else {
        carouselLis[right].style.transition = 'none';
    }
}

// 封装归位
function setTransform(dx) {
    dx = dx || 0;
    carouselLis[left].style.transform = 'translateX(' + (-screenWidth + dx) + 'px)';
    carouselLis[center].style.transform = 'translateX(' + dx + 'px)';
    carouselLis[right].style.transform = 'translateX(' + (screenWidth + dx) + 'px)';
}
// 动态设置小圆点的active类
var pointsLis = points.querySelectorAll('li');

function setPoint() {
    for (var i = 0; i <p><span class="img-wrap"><img src="https://img.php.cn//upload/image/613/478/733/1546825414662137.jpg" title="1546825414662137.jpg" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p><p><strong>效果图:</strong></p><p><span class="img-wrap"><img src="https://img.php.cn//upload/image/113/780/418/1546825434914550.gif" title="1546825434914550.gif" alt="How to implement Touch carousel on mobile terminal using native js (code example)"></span></p>

The above is the detailed content of How to implement Touch carousel on mobile terminal using native js (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete