Several methods of implementing carousel images in JS

Several methods of implementing carousel images in JS

Carousel

The main idea is:

In the large container, there is a very long table, which is an integer multiple of the width of the container.

Then change the left attribute in the list style to achieve left and right sliding.

This article aims to control the sliding of five pictures , but seven pictures are used in HTML. The first and last pictures are repeated. The reason will be explained below.

insert image description here

By setting the overflow:hidden attribute to the container, we can ensure that only one image of the size of the container's viewport is displayed.

<body>
 <div id="container"> /*container*/
  <div id="wrap" style="left: -400px;"> /*List of pictures*/
   <div class="item item5">l5</div>
   <div class="item item1">1</div>
   <div class="item item2">2</div>
   <div class="item item3">3</div>
   <div class="item item4">4</div>
   <div class="item item5">5</div>
   <div class="item item1">r1</div>
  </div>
 </div>
 <div id="key"> /*Set button*/   
  <div id="list"> /*Click the small circle to switch to a fixed image*/
   <div class="btn1 btnNum">1</div>
   <div class="btn2 btnNum">2</div>
   <div class="btn3 btnNum">3</div>
   <div class="btn4 btnNum">4</div>
   <div class="btn5 btnNum">5</div>
  </div>
  <div id="btn"> /*Buttons for switching left and right*/
   <button class="left">←</button>
   <button class="right">→</button>
  </div>
 </div>
</body>

CSS:

You can set the flex property for the wrap list to display the images in one line. Other layouts can be made according to your needs.

Note that the inline style left is set in the node with id="wrap"d. Because when switching pictures, I use the left attribute, and if I don’t set the left attribute, I can’t find the left attribute when setting the style in DOM.

<style>
  #container {
   width: 400px;
   height: 300px;
   border: 8px rgb(8, 8, 8) solid;
   margin: 0 auto;
   margin-top: 150px;
   overflow: hidden;
   position: relative;
  }
  #wrap {
   width: 2800px;
   height: 300px;
   display: flex;
   position: relative;
  }
  .item {
   flex: 1;
   width: 400px;
   height: 300px;
  }
  .item1 {
   background-color: rosybrown;
  }
  .item2 {
   background-color: rgb(12, 226, 37);
  }
  .item3 {
   background-color: rgb(212, 221, 29);
  }
  .item4 {
   background-color: rgb(61, 27, 182);
  }
  .item5 {
   background-color: rgb(221, 23, 145);
  }
  #key {
   width: 400px;
   height: 300px;
   margin: 0 auto;
  }
  #list {
   width: 400px;
   height: 40px;
   display: flex;
   justify-content: center;
  }
  #list div {
   margin-top: 10px;
   margin-left: 10px;
   width: 20px;
   height: 20px;
   background-color: rgb(13, 162, 221);
   text-align: center;
   border-radius: 45%;
   opacity: 0.6;
  }
  #list div:hover {
   cursor: pointer;
   opacity: 1;
  }
  #btn {
   width: 400px;
   text-align: center;
  }
 </style>

This is the complete style

insert image description here

Each color represents a picture and is numbered in sequence. The starting position is the second picture.

As for why there is an extra duplicate picture placed at both ends of the first and last picture, it is so that when creating a sliding effect , the last picture (the second to last picture, pink and purple) can continue to slide smoothly to the right to the first picture (actually the second picture in this picture, light brown). When you slide the first picture (the second one in this picture, light brown) to the left, you can slide smoothly to the last picture (actually the second to last picture). Continue reading below.

1. Multiple carousel modes

The carousel must be positioned, and the left attribute of the wrap list must be modified to make it move.

Initialize some data first

var wrap = document.getElementById('wrap');
var nowleft = -400; //Used to store the value of left in the current listvar currIndex = 1; //Used to store the current image number//Locate several buttonsvar btnNum = document.getElementsByClassName('btnNum'); //Small circlevar right = document.getElementsByClassName('right')[0]; //Button to slide to the rightvar left = document.getElementsByClassName('left')[0]; //Button to slide to the left

1.1 Timing automatic carousel effect

Only talk about the effect of automatic sliding to the left

Since it is an automatic rotation, the setInterval() timer is indispensable to keep it in continuous rotation.

function next() {
  setInterval(function() { //Set the image to switch every two seconds wrap.style.transition = 'left 1s' //Set the transition sliding effect nowleft = parseInt(wrap.style.left) - 400; //After switching once, nowleft should be reduced (i.e. slide to the left) by the width of one image wrap.style.left = nowleft + 'px'; //Then assign nowleft to the left attribute of wrapif(parseInt(wrap.style.left) == -2400) { //After judging the last one, secretly change back to the beginning setTimeout(() => {
       wrap.style.transition = 'none' //Because it is changed back secretly, the transition effect must be cancelled nowleft = -400;
       wrap.style.left = nowleft + 'px'
      },1200) // Ensure that the timer time is greater than the transition time and less than the time of each rotation}
  },2000)
}

/ Because wrap.style.left returns a string with px, you can use parseInt to get the previous value /

1.2 Press the right slide button

right.addEventListener('click',function() {
  if(nowleft >= -2000){ //Judge whether it is the last picture, if not, start sliding nowleft -= 400;
   wrap.style.transition = 'left 1s';
   wrap.style.left = nowleft + 'px';
  }
  if(nowleft == -2400) { //If we reach the last picture, we will secretly switch back to the first picture setTimeout(() => {
    wrap.style.transition = 'none';
    nowleft = -400;
    wrap.style.left = nowleft + 'px';
   },1020)
  }
})

1.3 Small circle switching pictures

for(let i = 0; i < btnNum.length; i++) {
  btnNum[0].style.opacity = 1;
  btnNum[i].addEventListener('click',function() {
   wrap.style.transition = 'left 1s';
   for(let j = 0; j < btnNum.length; j++) {
    btnNum[j].style.opacity = '0.6';
   }
   btnNum[i].style.opacity = 1;
   nowleft = nowleft - (i+1 - currIndex)*400;
   currIndex = i + 1;
   wrap.style.left = nowleft + 'px';
})

In fact, the operation of secretly switching from the last picture to the first picture in this article is flawed, because it takes 1 second to slide the picture with sequence number 5 to the picture with sequence number r1, but wrap.style.left changes directly and does not change with the displacement during the transition period. Therefore, it is somewhat difficult to control the time to completely slide sequence number 5 to r1 and then secretly switch to sequence number 1.

For example, you can switch to sequence number 4 by clicking 3 times in a row from sequence number 1. Of course, it is not possible to click three times in succession from sequence number 5. When R1 switches to sequence number 1, there is no response to the click effect, so the interaction difference here will easily feel awkward.

If you want to improve this awkward bug, you can use anti-shake to improve it.

This concludes this article on several methods of implementing carousel images natively with JS. For more relevant JS native carousel content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript implements circular carousel
  • js to write the carousel effect
  • Implementing a simple carousel based on JavaScript
  • JavaScript imitates Jingdong carousel effect
  • JavaScript Dom implements the principle and example of carousel
  • Native js to achieve seamless carousel effect
  • js to achieve mobile carousel sliding switch
  • javascript to realize the scroll wheel carousel picture
  • Sample code for a simple seamless scrolling carousel implemented with native Js

<<:  Steps to transplant the new kernel to the Linux system

>>:  Python3.6-MySql insert file path, the solution to lose the backslash

Recommend

The w3c organization gives style recommendations for html4

This is the style recommendation given by the W3C ...

Detailed explanation of the use of MySQL group links

Grouping and linking in MYSQL are the two most co...

The 6 Most Effective Ways to Write HTML and CSS

This article shares the 6 most effective methods,...

Do you know all 24 methods of JavaScript loop traversal?

Table of contents Preface 1. Array traversal meth...

Two methods of restoring MySQL data

1. Introduction Some time ago, there were a serie...

Detailed explanation of the basic commands of Firewalld firewall in Centos7

1. Basics of Linux Firewall The Linux firewall sy...

HTML table tag tutorial (45): table body tag

The <tbody> tag is used to define the style...

How to Completely Clean Your Docker Data

Table of contents Prune regularly Mirror Eviction...

Pure HTML+CSS to achieve Element loading effect

This is the effect of the Element UI loading comp...

MySQL 5.7 deployment and remote access configuration under Linux

Preface: Recently I am going to team up with my p...

Logrotate implements Catalina.out log rotation every two hours

1. Introduction to Logrotate tool Logrotate is a ...

Linux installation MySQL tutorial (binary distribution)

This tutorial shares the detailed steps of instal...

Detailed explanation of Cgroup, the core principle of Docker

The powerful tool cgroup in the kernel can not on...

Basic learning and experience sharing of MySQL transactions

A transaction is a logical group of operations. E...