Rotation diagram of mobile terminal (written in native JS)

Posted by SueHubert on Wed, 02 Feb 2022 09:15:06 +0100

Rotation diagram of mobile terminal (written in native JS)

1, Realize the following functions:

Can automatically play pictures
You can drag your finger to play the carousel

2, Implementation steps

  1. Auto play function:

① Start timer

② The translate of CSS3 can be used to move the mobile terminal. Note that you can move without adding using translate

③ If you want the picture to move gracefully, you need to add a transition effect

  1. Autoplay function - Seamless scrolling:

① Note that our judgment condition is to wait until the picture scrolls, that is, after the transition is completed

② At this time, you need to add the detection transition completion event transitionend

③ Judgment condition: if the index number is equal to 3, it means that you go to the last picture, and the index number should be restored to 0

④ At this time, the picture needs to remove the transition effect, and then move

The principle of seamless scrolling on the PC side is to clone the first picture and then add it to the ul's appendChild

Copy the first li of ul and put it at the end of ul
When the picture scrolls to the last cloned picture, let ul quickly jump to the far left without Animation: left is 0
At the same time, num is assigned to 0, and you can scroll the picture again
This method is still used at the mobile end, but it should be added that due to the effect of finger dragging at the mobile end, in order to avoid blank when the first picture is dragged forward, we also need to clone the last picture in front of the first one, which is as follows:

3. Effect of small round dots following changes:

① Select the one with li current class name in ol and remove the class name

② Put the current thought in quotation marks (add)

③ However, it will change after the transition, so this function should be written into the transitionend event

  1. Finger slide carousel

① The essence is ul following the finger movement, which is simply the drag element function of the mobile end

② Touch element: touchstart: get the initial coordinates of the finger

③ Move the finger touchmove: calculate the sliding distance of the finger and move the box

④ Touch end: different situations according to the sliding distance

⑤ If the moving distance is less than a certain pixel, it will rebound to the original position

⑥ If the moving distance is greater than a certain pixel, slide to the previous or next one

Performance optimization 1: when we click on the picture of the rotation chart, we don't want to move. At this time, when our fingers leave, we need to execute a large piece of code. The optimization method is: add a flag global variable. Only when the finger really moves, can a series of code operations of finger leaving be executed

Performance optimization 2: if the screen is long, the finger may scroll the screen while moving the carousel. The optimization method is to cancel the default behavior of scrolling the screen. Add e.preventDefault() to the touchmove event; Just.

3, Page layout

    <div class="focus">
        <ul>
            <li><img src="upload/focus3.jpg" alt=""></li>
            <li><img src="upload/focus1.jpg" alt=""></li>
            <li><img src="upload/focus2.jpg" alt=""></li>
            <li><img src="upload/focus3.jpg" alt=""></li>
            <li><img src="upload/focus1.jpg" alt=""></li>
        </ul>
        <!-- Small circle in the rotation chart -->
        <ol>
            <li class="current"></li>
            <li></li>
            <li></li>
        </ol>
    </div>
    <!-- Focus map module end -->

4, Focus module style

.focus {
    overflow: hidden;
    position: relative;
    padding-top: 44px;
}
.focus img {
    width: 100%;
}
.focus ul {
    /* ul Without height, the child elements inside are floating, which will inevitably lead to format confusion
    Therefore, you need to clear the float */
    overflow: hidden;
    width: 500%;
    /* Display the first picture instead of the third picture you copied */
    margin-left: -100%;
}
.focus ul li {
    float: left;
    /* Note: the width of the picture is 100%, which is full of the parent box. If the parent box of the picture is small and li has no width, find ul
       The width of ul is set to 500%, so the width of the picture is also lengthened
       Therefore, it is necessary to set the width of li, and each small li accounts for 1 / 5 of ul */
    width: 20%;
}
.focus ol {
    position: absolute;
    bottom: 5px;
    right: 5px;
    margin: 0;
}
.focus ol li {
    /* By making it an inline block element, you can float a row of displays */
    display: inline-block;
    width: 5px;
    height: 5px;
    border-radius: 2px;
    background-color: #fff;
    list-style: none;
    transition: all .3s;
}
.focus ol li.current {
    width: 15px;
}

5, JS logic code

window.addEventListener('load', function() {
    // 1. Get element
    var focus = document.querySelector('.focus');
    var ul = focus.children[0];
    var ol = focus.children[1];
    // Get the width of focus
    var w = focus.offsetWidth;
    // 2. Use the timer to automatically rotate pictures
    var index = 0;
    var timer = setInterval(function() {
        index++;
        var translateX = -index * w;
        // Add animation effect
        ul.style.transition = 'all .3s';
        ul.style.transform = 'translateX(' + translateX + 'px)';
    }, 2000);
    // Wait until the transition is completed, then judge and listen for the transition end event
    ul.addEventListener('transitionend', function() {
        // Seamless rolling
        if (index >= 3) {
            index = 0;
            // Remove the transition effect, so that ul can jump to the target position quickly
            ul.style.transition = 'none';
            // Continue scrolling the picture by multiplying the latest index number by the width
            var translateX = -index * w;
            ul.style.transform = 'translateX(' + translateX + 'px)';
        } else if (index < 0) {
            index = 2;
            // Remove the transition effect, so that ul can jump to the target position quickly
            ul.style.transition = 'none';
            // Continue scrolling the picture by multiplying the latest index number by the width
            var translateX = -index * w;
            ul.style.transform = 'translateX(' + translateX + 'px)';
        }
        // 3. Small dots follow the change
        // Select the class name li with current in ol and remove the class name remove
        ol.querySelector('.current').classList.remove('current');
        // Add the current class name add to the li of the current index number
        ol.children[index].classList.add('current');
    });
    // 4. Finger sliding rotation chart
    // Touch element touchstart: get the initial coordinates of the finger
    var startX = 0;
    var moveX = 0;  // This moving distance will be used later, so it should be defined as a global variable
    var flag = false;  //Used to mark whether the finger really moves or just clicks
    ul.addEventListener('touchstart', function(e) {
        startX = e.targetTouches[0].pageX;
        // Stop the timer when your finger touches it
        clearInterval(timer);
    });
    // Move the finger touchmove: calculate the sliding distance of the finger and move the box
    ul.addEventListener('touchmove', function(e) {
        // Calculate the moving distance
        // e.targetTouches[0] is the first finger, [1] is the second finger
        moveX = e.targetTouches[0].pageX - startX;
        // Move the box: the original position of the box + the distance the finger moves
        var translateX = -index * w + moveX;
        // When you drag with your fingers, you don't need animation effect, so you need to cancel the transition effect
        ul.style.transition = 'none';
        ul.style.transform = 'translateX(' + translateX + 'px)';
        flag = true;
        e.preventDefault();   //Organize the behavior of scrolling the screen
    });
    // When the finger leaves, judge whether to rebound or play the previous or next one according to the moving distance
    ul.addEventListener('touchend', function(e) {
        // The following code is executed only after the finger has been moved
        if (flag) {
            //(1) If the moving distance is greater than 50 pixels, the previous or next picture will be played
            if (Math.abs(moveX) > 50) {
                // If it is right sliding, it is playing the previous one, and moveX is a positive value
                if (moveX > 0) {
                    index--;
                } else {
                    // If it is left sliding, it means playing the next one, and moveX is a negative value
                    index++;
                }
                // Multiply the width with the latest index
                var translateX = -index * w;
                ul.style.transition = 'all .3s';
                ul.style.transform = 'translateX(' + translateX + 'px)';
            } else {
                //(2) If the moving distance is less than 50 pixels, it will rebound
                var translateX = -index * w;
                ul.style.transition = 'all .1s';
                ul.style.transform = 'translateX(' + translateX + 'px)';
            }
        }        
        // Restart the timer when your fingers leave
        // Note: before starting the timer, clear the previous timer to ensure that there is only one timer running at present
        clearInterval(timer);
        timer = setInterval(function() {
            index++;
            var translateX = -index * w;
            // Add animation effect
            ul.style.transition = 'all .3s';
            ul.style.transform = 'translateX(' + translateX + 'px)';
        }, 2000);
    });
});

Topics: Javascript Front-end css3