JS code realizes page switching effect

  • 2021-10-24 18:36:08
  • OfStack

This article example for everyone to share the JS code to achieve page switching effect of the specific code, for your reference, the specific content is as follows

HTML+CSS section

Add all pages, and buttons for the previous page, specific page, and the next page.
Set div style, by default, page 1 is displayed and other pages are hidden.


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <style>
  .item {
  display: none;
  width: 300px;
  height: 400px;
  overflow: hidden;
  position: relative;
  }  
  .item>img {
  width: 100%;
  height: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  } 
  .item.active {
  display: block;
  }
 </style>
 </head>
 <body>
 <div>
  <button class="prev" > Upper 1 Page </button>
  <button class="btn">1</button>
  <button class="btn">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="next" > Under 1 Page </button>
 </div>
 <div>
  <div class="item active"><img src="img/1.png" height="1191" width="820" /></div>
  <div class="item"><img src="img/2.png" height="1191" width="820" /></div>
  <div class="item"><img src="img/3.png" height="1191" width="820" /></div>
  <div class="item"><img src="img/4.png" height="1191" width="820" /></div>
 </div>
 </body>
</html>

js Part

Realize the function of the page by pressing buttons


<script type="text/javascript">
 // Encapsulation function, the part of the picture display, passing in the obtained div , and the serial number that was clicked 
 function toggle(eles, active) {
  for(var i = eles.length; i--;) {
   eles[i].className = "item"; // Let all of them first div Hide 
  }
  eles[active].className = "item active";// Then let the clicked serial number correspond to div  Display 
  }
  // Get the key and div
  var aBtn = document.getElementsByClassName("btn");
  var aIem = document.getElementsByClassName("item");
  var prev = document.getElementsByClassName("prev");
  var next = document.getElementsByClassName("next");
  var nowPage = 0; // Defines the current page, with the default value of 0 ; 
    
  for(var i = aBtn.length; i--;) {
   aBtn[i].tab = i;
   aBtn[i].onclick=function(){
   toggle(aIem,this.tab);
   nowPage=this.tab; // After being clicked, save the serial number of the current page 
   }
  }
   // Under 1 Page 
  next[0].onclick = function () {  
   nowPage++;   
   nowPage %= aBtn.length;
   toggle(aIem,nowPage);
  }
  // Upper 1 Page 
  prev[0].onclick=function(){
  nowPage--;
  if(nowPage ==-1){
   nowPage = aBtn.length-1;
  }
 toggle(aIem,nowPage);  
 }
</script>

Related articles: