In the team, I was asked suddenly how to implement carousel images. I have been in the front-end field for more than a year, but I haven't written it myself for a long time. I have always used a plug-in to write it in Daniu. Today I will write a simple tutorial suitable for beginners to learn. Of course, there are many implementation principles and design patterns of carousel diagrams. What I am talking about here is to implement them using process-oriented functional programming. Compared with object-oriented design patterns, the code will inevitably appear bloated and redundant. But the lack of object-oriented abstraction is very suitable for novices to understand and learn. Students who are already in BAT hope to squirt less. You can also give more suggestions.
The principle of carousel diagram:
A series of pictures of equal sizes are tiled, using CSS layout to display only one picture, and the rest are hidden. Automatic playback is achieved by calculating the offset using the timer, or switching pictures by manually clicking on events.
Html layout
First, the parent container container stores all contents, and the child container list contains pictures. Subcontainer buttons store button dots.
<div id="container"> <div id="list" style="left: -600px;"> <img src="img/5.jpg" /> <img src="img/1.jpg" /> <img src="img/2.jpg" /> <img src="img/2.jpg" /> <img src="img/3.jpg" /> <img src="img/4.jpg" /> <img src="img/5.jpg" /> <img src="img/1.jpg" /> </div> <div id="buttons"> <span index="1"></span> <span index="2"></span> <span index="3"></span> <span index="3"></span> <span index="4"></span> <span index="5"></span> </div> <a href="javascript:;" id="prev"><</a> <a href="javascript:;" id="next">></a> </div>
Optimize, seamless scrolling.
When you switch from the last image to the first image, there is a big gap, and use two auxiliary images to fill this gap.
Here is a seamless scrolling, look at the code directly, copy the last picture before placing the first picture, and copy the first picture behind the last picture. And, hide the first picture auxiliary image (actually the fifth picture actually displayed, so set style="left: -600px;")
CSS modification
1. Understanding box model, document flow, and absolute positioning issues.
2. Pay attention to the overflow:hidden of the list; only display a picture of the window and hide the left and right sides.
3. Make sure that each span layer in the buttons is topped and set it to the topmost. (z-index:999)
* {margin: 0;padding: 0;text-decoration: none;}body {padding: 20px;}#container {width: 600px;height: 400px;border: 3px solid #333;overflow: hidden;position: relative;}#list {width: 4200px;height: 400px;position: absolute;z-index: 1;}#list img {width: 600px;height: 400px;float: left;}#buttons {position: absolute;height: 10px;width: 100px;z-index: 2;bottom: 20px;left: 250px;}#buttons span {cursor: pointer;float: left;border: 1px solid #fff;width: 10px;height: 10px;border-radius: 50%;background: #333;margin-right: 5px;}#buttons .on {background: orangered;}.arrow {cursor: pointer;display: none;line-height: 39px;text-align: center;font-size: 36px;font-weight: bold;width: 40px;height: 40px;position: absolute;z-index: 2;top: 180px;background-color: RGBA(0, 0, 0, .3);color: #fff;}.arrow:hover {background-color: RGBA(0, 0, 0, .7);}#container:hover .arrow {display: block;}#prev {left: 20px;}#next {right: 20px;}Js
First, we first realize the effect of manually clicking the left and right arrows to switch the picture:
window.onload = function() {var list = document.getElementById('list');var prev = document.getElementById('prev');var next = document.getElementById('next');function animate(offset) {//What is obtained is style.left, which is the distance to get relative to the left, so after the first picture, style.left is all negative, // And style.left is a string, which needs to be rounded with parseInt() to convert it into a number. var newLeft = parseInt(list.style.left) + offset;list.style.left = newLeft + 'px';}prev.onclick = function() { animate(600);}next.onclick = function() { animate(-600);}}After running, we will find that if you keep clicking the right arrow, there will be a blank, and you cannot return to the first picture. Click the left arrow to return to the first image.
Using Google Chrome F12, the reason is that we use the offset left to obtain the picture. When we see that the left value is less than 3600, there will be blank if there is no 8th picture, so we need to make a judgment on the offset here.
Add this paragraph to the animate function:
if(newLeft<-3000){list.style.left = -600 + 'px';}if(newLeft>-600){list.style.left = -3000 + 'px';}OK, run it, no problem. Carousel pictures, as the name suggests, are pictures that you can move. At this time, we need to use the browser's built-in object timer.
For timers, it is necessary to explain the difference between setInterval() and setTimeout. Simply put, setInterval() is executed multiple times, and setTimeout() is executed only once.
For more specific usage, you can click the link to view the difference: window.setInterval window.setTimeout.
Here we use setInterval() because our image needs to be scrolled loop. Insert below
var timer;function play() {timer = setInterval(function() {prev.onclick()}, 1500)}play();Run, ok!
However, when we want to carefully look at a certain image, we need to stop the image and we can just clear the timer. This method is used here.
Here, we need to operate on its DOM and need to obtain the entire carousel map area;
var container = document.getElementById('container');function stop() {clearInterval(timer);}container.onmouseover = stop;container.onmouseout = play;But here, a carousel picture has been basically completed, and some students will ask, so it is so simple. Did you see the row of small dots under the picture? I've added features to you.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Here is the upgraded version:
var buttons = document.getElementById('buttons').getElementsByTagName('span');var index = 1;function buttonsShow() {//The previous style needs to be cleared for (var i = 0; i < buttons.length; i++) {if (buttons[i].className == 'on') {buttons[i].className = '';}}//The array starts from 0, so index needs -1buttons[index - 1].className = 'on';}prev.onclick = function() {index -= 1;if (index < 1) {index = 5;}buttonsShow();animate(600);}next.onclick = function() {// Due to the effect of the timer above, the index will continue to increase. We only have 5 small dots, so we need to make a judgment index += 1;if (index > 5) {index = 1;}buttonsShow();animate(-600);}It seems much more normal now, but we want to click on one of the small dots at any time with the mouse and switch to the corresponding picture. The same principle is, we still need to find the corresponding picture through the offset.
for (var i = 0; i < buttons.length; i++) {buttons[i].onclick = function() {//Optimize, click the current dot in the current image and do not execute the following code. if (this.className == "on") {return;}/* Offset get: Here you get the position where the mouse moves to the dot, use this to bind the index to the object buttons[i], go to Google this usage *//* Since the index here is a custom attribute, you need to use the DOM2-level method getAttribute() to get the attribute of the custom index*/var clickIndex = parseInt(this.getAttribute('index'));var offset = 600 * (clickIndex - index);animate(offset);//Storage the position after the mouse click, and use it to display the dots as normal index = clickIndex;buttonsShow();}}Everyone, you may have discovered that this carousel picture is a bit strange and unpredictable. It switches to the left, so rewrite it:
function play() {//Switch the carousel image to switch the image to the right timer = setInterval(function () {next.onclick();}, 2000)} <!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">* {margin: 0;padding: 0;text-decoration: none;}body {padding: 20px;}#container {width: 600px;height: 400px;border: 3px solid #333;overflow: hidden;position: relative;}#list {width: 4200px;height: 400px;position: absolute;z-index: 1;}#list img {width: 600px;height: 400px;float: left;}#buttons {position: absolute;height: 10px;width: 100px;z-index: 2;bottom: 20px;left: 250px;}#buttons span {cursor: pointer;float: left;border: 1px solid #fff;width: 10px;height: 10px;border-radius: 50%;background: #333;margin-right: 5px;}#buttons .on {background: orangered;}.arrow {cursor: pointer;display: none;line-height: 39px;text-align: center;font-size: 36px;font-weight: bold;width: 40px;height: 40px;position: absolute;z-index: 2;top: 180px;background-color: RGBA(0, 0, 0, .3);color: #fff;}.arrow:hover {background-color: RGBA(0, 0, 0, .7);}#container:hover .arrow {display: block;}#prev {left: 20px;}#next {right: 20px;}</style><script type="text/javascript">/* Knowledge point: *//* this usage*//* DOM event*//* timer*/window.onload = function () {var container = document.getElementById('container');var list = document.getElementById('list');var buttons = document.getElementById('buttons').getElementsByTagName('span');var prev = document.getElementById('prev');var next = document.getElementById('next');var index = 1;var timer;function animate(offset) {//What is obtained is style.left, which is the distance to get relative to the left, so after the first picture, style.left is all negative, // And style.left is a string, which needs to be rounded with parseInt() to convert it into a number. var newLeft = parseInt(list.style.left) + offset;list.style.left = newLeft + 'px';//Infinite scrolling judgment if (newLeft > -600) {list.style.left = -3000 + 'px';}if (newLeft < -3000) {list.style.left = -600 + 'px';}}function play() {//Repeated execution timer = setInterval(function () {next.onclick();}, 2000)}function stop() {clearInterval(timer);}function buttonsShow() {//Clear the style of the previous small dot for (var i = 0; i < buttons.length; i++) {if (buttons[i].className == "on") {buttons[i].className = "";}}//The array starts from 0, so index needs -1buttons[index - 1].className = "on";}prev.onclick = function () {index -= 1;if (index < 1) {index = 5}buttonsShow();animate(600);};next.onclick = function () {// Due to the effect of the timer above, the index will continue to increase. We only have 5 small dots, so we need to make a judgment index += 1;if (index > 5) {index = 1}animate(-600);buttonsShow();};for (var i = 0; i < buttons.length; i++) {buttons[i].onclick = function () {//Optimize, click the current small dot in the current image and do not execute the following code. if (this.className == "on") {return;}/* Here we get the position where the mouse moves to the dot, use this to bind the index to the object buttons[i], go to Google this usage*//* Since the index here is a custom attribute, you need to use the DOM2-level method getAttribute() to get the attribute of the custom index*/var clickIndex = parseInt(this.getAttribute('index'));var offset = 600 * (clickIndex - index); //This index is indexanimate(offset); index = clickIndex; //Storage the position after the mouse click, and use it to display the dotsShow();}}container.onmouseover = stop;container.onmouseout = play;play();}</script></head><body><div id="container"><div id="list" style="left: -600px;"><img src="img/5.jpg"/><img src="img/1.jpg"/><img src="img/2.jpg"/><img src="img/3.jpg"/><img src="img/4.jpg"/><img src="img/5.jpg"/><img src="img/5.jpg"/><img src="img/2.jpg"/><img src="img/3.jpg"/><img src="img/4.jpg"/><img src="img/5.jpg"/><img src="img/1.jpg"/></div><div id="buttons"><span index="1"></span><span index="2"></span><span index="3"></span><span index="4"></span><span index="5"></span></div><a href="javascript:;" id="prev"></a><a href="javascript:;" id="next">></a></div></body></html>The above is the simple JS carousel code introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!