foreword
Tearing the carousel by hand may be a nightmare for many front-end beginners. In order to examine the basic knowledge of candidates, many companies usually ask a question about tearing the carousel by hand. Although many people look down on this interview question, many people are unable to write correct code, even developers who have been working for a while.
In fact, it is not difficult to tear the carousel map by hand. As long as you understand the principle, it is very simple to implement. Of course, the key point is to have a solid JS foundation.
Next, I will take you to implement a simple carousel diagram.
1. Principle introduction
The principle of the carousel map is actually not too complicated. It can be summarized into two points:
- use of positioning
- Use of timer
The above two points are mainly two important points in the implementation method of the carousel map. Through the following two pictures, you can more easily understand the principle of the carousel map:
The boxes 1, 2, 3, 4... in the above picture can be seen as pictures, and they are arranged in sequence horizontally. There is also a parent box in the outermost layer, and its width is exactly the width of a picture. The first picture is not set to hide the excess part, and the second picture hides the excess part.
Let the position of our image change continuously, let it appear in the visible area, and add some animations, it becomes the carousel image we want.
2. The effect achieved
Knowing the general principle, then let's take a look at the effect that needs to be achieved:
- Automatic image rotation
- The carousel is animated
- Click the left and right buttons to switch
- Click the number button to switch to the corresponding picture
- Number buttons have a selected effect
- Mouse over to stop autoplay
3. Specific implementation
3.1 HTML Layout
As can be seen from the above figure, the HTML layout is very simple and is mainly divided into three parts: left and right switching buttons, image list, and bottom digital switching buttons.
code show as below:
<div class="container"> <!-- Picture list --> <ul class="ul-img"> <li class="li-img">1</li> <li class="li-img">2</li> <li class="li-img">3</li> <li class="li-img">4</li> <li class="li-img">5</li> </ul> <!-- Previous and next buttons --> <div class="prev"> <span><</span> </div> <div class="next"> <span>></span> </div> <!-- Digital toggle button --> <div class="num-box"> <ul class="num-ul"> <li data-index="0">1</li> <li data-index="1">2</li> <li data-index="2">3</li> <li data-index="3">4</li> <li data-index="4">5</li> </ul> </div> </div> copy code
One thing to note here is that we have added a custom attribute to the li tag of the digital switch button, because we need to use it later in js to determine which image corresponds to, and it is convenient to set the selection effect.
3.2 CSS styles
We need to arrange the picture list in a row, and make the outermost box set beyond hidden, and the other two parts can be positioned to the corresponding position, the code is as follows:
.container { position: relative; width: 600px; height: 400px; margin: 0 auto; background-color: gray; overflow: hidden; } .ul-img { position: absolute; display: flex; width: 4200px; height: 400px; left: 0; padding: 0; margin: 0; } .li-img { list-style: none; width: 600px; height: 400px; display: flex; align-items: center; justify-content: center; background-color: aquamarine; font-size: 30px; font-weight: 800; border: 1px solid #ccc; } /* previous, next */ .prev, .next { position: absolute; height: 400px; width: 80px; display: flex; justify-content: center; align-items: center; top: 0; } .prev { left: 0; } .next { right: 0; } .prev span, .next span { display: block; color: #fff; width: 40px; height: 40px; display: flex; justify-content: center; align-items: center; background-color: rgba(0, 0, 0, 0.5); border-radius: 50%; cursor: pointer; } /* Digital toggle button */ .num-box { position: absolute; left: 50%; bottom: 20px; transform: translate(-50%, 0); z-index: 2; } .num-ul { list-style: none; margin: 0; padding: 0; display: flex; } .num-ul li { height: 20px; width: 20px; border-radius: 50%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; font-size: 9px; color: #fff; margin: 0 4px; cursor: pointer; user-select: none; } copy code
At this time, the basic style comes out, but it cannot be rotated yet, and the first picture is always displayed:
At this point, our basic layout has been realized, but it is still a long way from our needs, and the focus is on the js part.
3.3 JS code
JS logic code is the core part of realizing our entire needs. Let’s go over the code as a whole first, and then we will explain:
// get element node var containerDom = document.getElementsByClassName("container")[0]; // container var ulDom = document.getElementsByClassName("ul-img")[0]; // picture box var prevDom = document.getElementsByClassName("prev")[0].firstElementChild; // previous button var nextDom = document.getElementsByClassName("next")[0].firstElementChild; // next button var numUlDom = document.getElementsByClassName("num-ul")[0]; // Number button parent container var numList = document .getElementsByClassName("num-ul")[0] .getElementsByTagName("li"); // List of digital toggle buttons // define global variables var currentIndex = 0; // currently displayed image index var timer = null; // Autoplay timer numList[currentIndex].style.backgroundColor = "#ccc"; // the first number is selected by default // Previous prevDom.addEventListener("click", prevFun); // next nextDom.addEventListener("click", nextFun); // Move the mouse into the container to stop autoplay containerDom.addEventListener("mouseenter", stopAutoPlay); // Move the mouse out of the container to start autoplay containerDom.addEventListener("mouseleave", autoPlay); // Number button click event numUlDom.addEventListener("click", numClick); // Turn on autoplay autoPlay(); // switch to previous function prevFun() { ulDom.style.transition = "0.5s"; numList[currentIndex].style.backgroundColor = ""; // Clear the style of the previous button if (currentIndex === 0) { ulDom.style.transition = "0s"; // Clear animation for seamless scrolling currentIndex = 4; } else { --currentIndex; } ulDom.style.left = `-${currentIndex * 600}px`; numList[currentIndex].style.backgroundColor = "#ccc"; } // switch to next function nextFun() { ulDom.style.transition = "0.5s"; numList[currentIndex].style.backgroundColor = ""; // Clear the style of the previous button if (currentIndex === 4) { ulDom.style.transition = "0s"; // Clear animation for seamless scrolling currentIndex = 0; // replay the first } else { ++currentIndex; } ulDom.style.left = `-${currentIndex * 600}px`; numList[currentIndex].style.backgroundColor = "#ccc"; // set the button selection style } // Number button click event function numClick(e) { ulDom.style.transition = "0.5s"; let index = e.target.dataset.index; if (index == undefined) { return; } numList[currentIndex].style.backgroundColor = ""; // Clear the style of the previous button currentIndex = Number(index); numList[currentIndex].style.backgroundColor = "#ccc"; ulDom.style.left = `-${currentIndex * 600}px`; } // Loop function autoPlay() { timer = setInterval(nextFun, 1000); } // Turn off autoplay function stopAutoPlay() { // clear timer clearInterval(timer); } copy code
There are several main methods in js. We will understand one or two here. For example, we need to click the button to switch to the previous or next image. The main implementation methods are as follows:
function nextFun() { ulDom.style.transition = "0.5s"; numList[currentIndex].style.backgroundColor = ""; // Clear the style of the previous button if (currentIndex === 4) { ulDom.style.transition = "0s"; // Clear animation for seamless scrolling currentIndex = 0; // replay the first } else { ++currentIndex; } ulDom.style.left = `-${currentIndex * 600}px`; numList[currentIndex].style.backgroundColor = "#ccc"; // set the button selection style } copy code
When we click the toggle button style, first clear the selected style of the previous number button, and then determine whether it is the last picture or the first picture. We declare a global variable currentIndex to store the currently displayed image.
Then dynamically calculate and change the left distance of the picture to be displayed by currentIndex.
The principle of autoplay and clicking the number button to switch pictures is similar to this method, both of which need to calculate the left of the picture to be displayed.
3.4 Core Methods
In the js part, we have about five main methods:
- prevFun(): Click to switch to the previous one
- nextFun(): Click to switch to the next one
- numClick(e): Click the number button
- autoPlay(): Loop the carousel
- stopAutoPlay(): Turn off autoplay
Summarize
It is not difficult to realize the carousel map, the difficulty is whether you have patience. Carousel is nothing more than letting a certain picture in a row of pictures appear in the right area at the right time.
Of course, there are many ways and methods to realize the carousel map. For example, the carousel map can also be realized with pure CSS, which mainly depends on individual needs.