jQuery realizes the effect of simple carousel map

  • 2021-10-15 09:41:06
  • OfStack

In this paper, we share the specific code of jQuery to achieve simple carousel effect for your reference. The specific contents are as follows

Here is the way I use a timer to switch pictures every few seconds and then add two buttons to switch between the top one and the next one

1. Import jQuery file


<script src="jquery-3.5.1.js"></script>

2. Set the style of the picture


<style>
  *{
   margin: 0;
   padding: 0;
  }
  #box{
   width: 300px;
   height: 300px;
   border: 2px solid red;
  }
  #box img{
   position: absolute;
   display: none;
  }
  #box :first-child{
   display: block;
  }
  .page{
   list-style: none;
   display: flex;
   width: 300px;
   justify-content: space-around;
  }
  .page li{
   border: 1px solid red;
   border-radius: 50%;
   width: 20px;
   height: 20px;
   text-align: center;

  }
  .active{
   background: red;
  }
 </style>
 <script src="./jquery.js"></script>
</head>
<body>
 <div id="box">
  <img src="./img/1.jpg" alt="">
  <img src="./img/2.jpg" alt="">
  <img src="./img/3.jpg" alt="">
  <img src="./img/4.jpg" alt="">
 </div> 
 <ul class="page" id="page" >
  <li class="active">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
 </ul>
<button id="next"> Under 1 Zhang </button>
<button id="prev"> Upper 1 Zhang </button>

3 Realization of carousel of pictures


/*
  Absolute positioning  --  Stack up 
  Through subscript  --  Displays the current  -- Other brothers   Hide 
*/
  <script>
   var index=0;
    //  Moving method 
   function move(){
    index++;
    if (index>=$("#box img").length) {
     index=0;
    }
    $("#box img").eq(index).show().siblings().hide();
    $("#page li").eq(index).addClass("active").siblings().removeClass("active");
   }
   // Implementation method of timer 
   var t=setInterval(move,2000);
   // Moving the mouse over the picture will stop leaving and continue the carousel 
   $("#box").hover(function(){
    clearInterval(t)
   },function(){
    t=setInterval(move,2000)
   })

   $("#page li").click(function(){
    index= $(this).index() ;
    $("#box img").eq(index).show().siblings().hide();
    $("#page li").eq(index).addClass("active").siblings().removeClass("active");
   })
   // Under 1 Zhang's clicks 
   $("#next").click(function(){
    move();
   })
   // Upper 1 Zhang's clicks 
   $("#prev").click(function(){
    index--;
    //  It is judged that if the subscript exceeds the number of inherent pictures, the carousel is started from scratch 
    if (index<0) {
     index=$("#box img").length-1;
    }
    $("#box img").eq(index).show().siblings().hide();
    $("#page li").eq(index).addClass("active").siblings().removeClass("active");
   })

</script>

Related articles: