Native js encapsulation seamless carousel function

Native js encapsulation seamless carousel function

Native js encapsulated seamless carousel plug-in, for your reference, the specific content is as follows

illustrate:

This is a seamless carousel program written in native js and es5 syntax. The relevant APIs are encapsulated in the code, so that after introducing the carousel js file, you only need to add two lines of code in your own js file to achieve a basic seamless carousel effect on the web page.

The basic usage steps are: get the DOM element array, pass parameters to the carousel object, and the carousel object calls the automatic carousel method.

In addition to the basic timer automatic carousel function, the program also supports setting transition animation time, setting automatic carousel stop when the mouse moves into the element, setting carousel when clicking the left and right side buttons, and setting carousel when clicking the bottom button.

The program does not need to rely on CSS or HTML files, but requires your CSS and HTML layouts to follow certain rules.

Please note that this program does not support curve transition speed, and sometimes there will be a bug in the carousel image being disordered after switching the browser window. The problem cannot be found for the time being.

This program is just a simple encapsulation of the seamless carousel function by a beginner like me, and can only be used for learning and reference.

In addition to the carousel code, I will also give a sample program below.

Operation effect:

Ideas:

The arrangement order of all the slideshow elements is determined according to the direction of the slideshow. If the current slideshow has reached the boundary of all the slideshows, the last slideshow in the relative direction will be instantly moved to the corresponding position.
The minimum number of carousel images required to implement the carousel image using this method is 3. The cases where there are one or two carousel images need to be handled separately. In the case of one, copy and add two carousel image elements that are the same as the current carousel image. In the case of two, copy and add the current carousel image in sequence.

Compilation environment:

Chrome 86.0.4240.183

Code:

slide.js encapsulates the slideshow code

(function(window, undefined) {
 
 // Get the element CSS attribute value function getCss(elem, attr) {
  return elem.currentStyle ? 
   elem.currentStyle[attr] : 
   window.getComputedStyle(elem, null)[attr];
 }
 
 // Remove non-digits from the string, excluding negative signs function toInt(str) {
  var rex = /[^0-9]/ig;
  return Number((str[0] === '-' && str[1] !== '=') ? '-' + str.replace(rex, '') : str.replace(rex, ''));
 }
 
 // Encapsulate animation function, parameters: dom object, css attribute value object, animation execution time, callback after animation is completed function animation(elem, params, speed, callback) {
  for (var param in params) {
   (function(param) {
    
    var elemValue = toInt(getCss(elem, param)),
     targetValue = toInt(params[param]),
     currentDis = elemValue,
     unit = params[param].substr(params[param].indexOf('[A-Za-z]+') - 1);
    
    if (params[param].length > 2) {
     var prefix = params[param].substr(0, 2);
     
     if (prefix === '+=')
      targetValue = elemValue + targetValue;
     else if (prefix === '-=')
      targetValue = elemValue - targetValue;
    }
    
    var dis = (targetValue - elemValue) / speed,
     sizeFlag = targetValue < elemValue;
    
    var timer = setInterval(function() {
     
     elemValue = toInt(getCss(elem, param));
     
     if (sizeFlag) {
      if (currentDis <= targetValue) {
       clearInterval(timer);
       elem.style[param] = targetValue + unit;
      } else {
       currentDis += dis;
       elem.style[param] = currentDis + unit;
      }
     }
     else {
      if (currentDis >= targetValue) {
       clearInterval(timer);
       elem.style[param] = targetValue + unit;
      } else {
       currentDis += dis;
       elem.style[param] = currentDis + unit;
      }
     }
    }, 1);
    
   })(param);
  }
  
  if (typeof callback === 'function')
   callback();
 };
 
 
 // Move the carousel array to the right function rightRoundArrayMove() {
  
  var winsLen = wins.length;
  var lastWin = wins[winsLen - 1];
  
  for (var i = winsLen - 1; i > 0; i--) 
   wins[i] = wins[i - 1];
  
  wins[0] = lastWin;
 }
 
 // Rotate to the left function rightRound(time) {
  
  rightRoundArrayMove();
  
  wins.forEach(function(win, index) {
   (index === 0) ? 
    win.style.left = index * winWidth - winWidth + 'px' :
    animation(win, {left: '+=' + winWidth + 'px'}, time ? time : animationTime);
  });
 }
 
 //Rotate to the right function leftRound(time) {
  
  var winsLen = wins.length;
  var firstWin = wins[0];
  
  for (var i = 0; i < winsLen - 1; i++)
   wins[i] = wins[i + 1];
   
  wins[winsLen - 1] = firstWin;
  
  wins.forEach(function(win, index) {
   (index === wins.length - 1) ? 
    win.style.left = index * winWidth - winWidth + 'px' :
    animation(win, {left: '-=' + winWidth + 'px'}, time ? time : animationTime);
  });
 }
 
 
 var 
  // wins, btns, sbtns are used to save the constructor parameter wins, 
  btns, 
  sbtns, 
  // Window width winWidth,
  // Transition animation time (milliseconds), default is 100
  animationTime = 100,
  // Click the button to rotate the interval clickInterval = animationTime << 2,
  // Save the auto-rotation timer, timer interval, and whether to rotate to the right autoRoundTimer,
  qinterval,
  qisRight,
  //slide constructor, parameters: window array, button array, side button array slide = function(wins, btns, sbtns) {
   return new slide.prototype.init(wins, btns, sbtns);
  };
  
 
 slide.prototype = {
  
  // Initialize window elements init: function(awins, abtns, asbtns) {
   
   if (!awins)
    throw new Error('The window array cannot be empty.');
   
   wins = Object.values(awins), btns = abtns, sbtns = asbtns;
   
   // Handle the situation where there are less than 3 windows if (wins.length === 1) {
    var winParent = wins[0].parentNode;
    var winHTML = wins[0].outerHTML;
    winParent.innerHTML += winHTML + winHTML;
    wins = Object.values(winParent.children);
   }
   else if (wins.length === 2) {
    var winParent = wins[0].parentNode;
    winParent.innerHTML += wins[0].outerHTML + wins[1].outerHTML;
    wins = Object.values(winParent.children);
   }
   
   winWidth = wins[0].offsetWidth;
   
   wins.forEach(function(win, index) {
    win.style.position = 'absolute';
    win.index = index;
   });
   
   rightRoundArrayMove();
   
   wins.forEach(function(win, index) {
    win.style.left = index * winWidth - winWidth + 'px';
   });
  },
  
  // Set the transition animation time setAnimationTime: function(time) {
   animationTime = time;
   clickInterval = animationTime << 2;
  },
  
  // Automatic rotation, parameters: rotation time interval, whether to rotate right autoRound: function(interval, isRight) {
   autoRoundTimer = setInterval(function() {
        isRight ? rightRound() : leftRound();
       }, interval);
   qinterval = interval;
   qisRight = isRight;
  },
  
  // Side button click, the parameter is the side button element array, which can be passed in the constructor or passed now sideBtnClickRound: function(sabtns) {
   
   var leftBtn = sabtns ? sabtns[0] : sbtns[0],
    rightBtn = sabtns ? sabtns[1] : sbtns[1];
   
   var isclick = true;
   leftBtn.onclick = function () {
    if(isclick) {
     isclick=false;
     rightRound();
     setTimeout(function() { 
      isclick = true;
     }, clickInterval);
    }
   };
   
   rightBtn.onclick = function () {
    if(isclick) {
     isclick=false;
     leftRound();
     setTimeout(function() {
      isclick = true;
     }, clickInterval);
    }
   };
  },
  
  // Ordinary button click, parameters: ordinary button array, callback btnsClickRound: function(abtns, callback) {
   
   var ibtns = abtns ? abtns : btns;
   
   var isclick = true;
   
   ibtns.forEach(function(btn, index) {
    btn.onclick = function() {
     if(isclick) {
      isclick=false;
      
      if (typeof callback === 'function')
       callback(ibtns, btn, index);
      
      var poor = index - wins[1].index;
      var count = Math.abs(poor);
      if (poor < 0) {
       var absPoor = count;
       var timer = setInterval(function() {
        console.log((absPoor + 1))
           rightRound(animationTime / (absPoor + 2));
           if ((--count) === 0) 
            clearInterval(timer);
          }, animationTime);
      }
      else if (poor > 0) {
       var timer = setInterval(function() {
           leftRound(animationTime / (poor + 2));
           if ((--count) === 0) 
            clearInterval(timer);
          }, animationTime);
      }
      
      setTimeout(function() {
       isclick = true;
      }, clickInterval << 1);
     }
    }
   });
  },
  
  // Set the mouse to move in and cancel the automatic rotation, parameters: the element to move in, the callback of the element to move in, the callback of the element to move out setOverStop: function(box, overCallback, outCallback) {
   box.onmouseover = function(e) {
    clearInterval(autoRoundTimer);
    
    if (typeof overCallback === 'function')
     overCallback(e);
   }
   box.onmouseout = function(e) {
    slide.prototype.autoRound(qinterval, qisRight);
    
    if (typeof outCallback === 'function')
     outCallback(e);
   }
  }
 }
 
 slide.prototype.init.prototype = slide.prototype;
 window.slide = _slide = slide;
 
})(window);

test.js Test example js code:

onload = function() {
 
 var wins = document.querySelectorAll('.wins > li');
 var btns = document.querySelectorAll('.btns > li');
 var sideBtns = document.querySelectorAll('.side-btns > div');
 var box = document.querySelector('.box');
 
 var s = slide(wins, btns, sideBtns); // Create a carousel object, parameters: window dom array, bottom button dom array (optional),
 s.autoRound(2000); // Set automatic rotation s.setAnimationTime(200); // Set transition animation time s.setOverStop(box); // Set automatic rotation stop when the mouse moves into the element, parameters: DOM element moved in, callback of moved-in element, callback of moved-out element s.sideBtnClickRound(); // Set rotation when clicking the side button, parameters: button DOM array (optional)
 s.btnsClickRound(); // Set the rotation when the button below is clicked, parameters: button dom array (optional), callback}

HTML, CSS sample code

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title></title>
  <style type="text/css">
   * {
    margin: 0;
    padding: 0;
   }
   
   li {
    list-style: none;
   }
   
   .box {
    width: 1000px;
    height: 400px;
    margin: 20px auto;
    display: flex;
    align-items: center;
    position: relative;
    overflow: hidden;
   }
   
   .box > * {
    position: absolute;
   }
   
   .side-btns {
    width: inherit;
    height: 100px;
    display: flex;
    justify-content: space-between;
    z-index: 2;
   }
   
   .side-btns > div {
    width: 50px;
    height: inherit;
    text-align: center;
    line-height: 100px;
    font-size: 18px;
    background-color: rgba(0, 0, 0, .3);
    color: white;
    cursor: pointer;
    user-select: none;
   }
   
   .btns {
    width: inherit;
    height: 20px;
    display: flex;
    justify-content: flex-end;
    z-index: 2;
    position: absolute;
    bottom: 20px;
   }
   
   .btns > li {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    margin-right: 12px;
    cursor: pointer;
    background-color: rgba(0, 0, 0, .2);
   }
   
   .wins {
    width: inherit;
    height: inherit;
    display: flex;
   }
   
   .wins > li {
    width: inherit;
    height: inherit;
    flex-grow:0;
    flex-shrink:0;
   }
  </style>
  <script src="js/slide.js"></script>
  <script src="js/test.js"></script>
 </head>
 
 <body>
  <div class="box">
   <div class="side-btns">
    <div class="left-btn">&lt;</div>
    <div class="right-btn">&gt;</div>
   </div>
   
   <ul class="btns">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
   </ul>
   
   <ul class="wins">
    <li style="background-color: antiquewhite;">a</li>
    <li style="background-color: aquamarine;">b</li>
    <li style="background-color: green;">c</li>
    <li style="background-color: brown;">d</li>
   </ul>
  </div>
 </body>
</html>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of JavaScript axios installation and packaging case
  • In-depth analysis of homology and cross-domain, jsonp (function encapsulation), CORS principle
  • Vue.js manages the encapsulation of background table components
  • Detailed explanation of JavaScript object-oriented practice: encapsulation and dragging objects
  • Native JS encapsulation vue Tab switching effect
  • js implements a simple method of encapsulating jQuery and a detailed explanation of chain operations
  • js implements some functions of the input component in Element and encapsulates it into a component (example code)
  • JavaScript implements prototype encapsulation carousel
  • Encapsulation method of JavaScript slow motion animation function
  • JavaScript canvas encapsulation dynamic clock
  • About Jackson's JSON tool class encapsulation JsonUtils usage
  • Example code for JavaScript encapsulation of a singly linked list
  • Common front-end JavaScript method encapsulation

<<:  Django online deployment method of Apache

>>:  MySQL 8.0.12 installation configuration method and password change

Recommend

Vue3 slot usage summary

Table of contents 1. Introduction to v-slot 2. An...

Introduction to the use of common Dockerfile commands

Table of contents 01 CMD 02 ENTRYPOINT 03 WORKDIR...

Example of CSS3 to achieve div sliding in and out from bottom to top

1. First, you need to use the target selector of ...

Linux installation Redis implementation process and error solution

I installed redis today and some errors occurred ...

Detailed explanation of MySQL phantom reads and how to eliminate them

Table of contents Transaction Isolation Level Wha...

How to use Vue's idea to encapsulate a Storage

Table of contents background Function Purpose Ide...

Detailed tutorial on how to automatically install CentOS7.6 using PXE

1. Demand The base has 300 new servers, and needs...

Detailed explanation of how to install MySQL on Alibaba Cloud

As a lightweight open source database, MySQL is w...

js native waterfall flow plug-in production

This article shares the specific code of the js n...

OpenSSL implements two-way authentication tutorial (with server and client code)

1. Background 1.1 Problems A recent product testi...

Detailed explanation of vuex persistence in practical application of vue

Table of contents vuex persistence Summarize vuex...

Detailed explanation of query examples within subqueries in MySql

Where is my hometown when I look northwest? How m...

JavaScript canvas to achieve raindrop effects

This article example shares the specific code of ...