简单的jQuery旋转木马幻灯片计数器

时间:2019-12-06 03:50:07

标签: jquery html css carousel counter

我在网站的某个部分中有一个简单的基于文本的水平滑块,它可以左右滚动,这是由鼠标滚动控制的。我试图弄清楚如何显示幻灯片的当前索引和幻灯片的总数。例如1/4-并在滚动幻灯片时更新当前索引。

jQuery(function($) {
  var slideContainer = $('.inner-slide-container');
  var totalSlides = slideContainer.children().length;
  var firstSlide = slideContainer.index() + 1;

  $('.slide-num').html('<span class="slide-index">' + firstSlide + '</span>' + '/' + '<span class="slide-total">' + totalSlides + '</span>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider-container">
  <div class="inner-slide-container">
    <div id="slide1" class="slide active">
      <h3>This is Slide 1</h3>

      <p>Some content for slide 1</p>
    </div>

    <div id="slide2" class="slide">
      <h3>This is Slide 2</h3>

      <p>Some content for slide 2</p>
    </div>

    <div id="slide3" class="slide">
      <h3>This is Slide 3</h3>

      <p>Some content for slide 3</p>
    </div>

    <div id="slide4" class="slide">
      <h3>This is Slide 4</h3>

      <p>Some content for slide 4</p>
    </div>
  </div>
  <div class="slide-num"></div>
</div>

第一张幻灯片将获得“活动”类,然后在用户滚动时将“活动”类切换到下一张幻灯片,然后在向后滚动时将其反转。

我不知道从哪里开始,我已经看过使用$ .each和一个'for'循环,但是无法弄清楚在您更新“当前索引”时最好的方法是什么滚动浏览。

不是一个JS家伙,但以为我可以试一试,事实证明它比看上去要难一些。

任何感激或朝正确方向的推动将不胜感激。

4 个答案:

答案 0 :(得分:2)

//这是带有索引的简单易用的轮播滑块,希望此代码可以帮助您满足要求

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


<div class="num"></div>

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-wrap="false" data-interval="false">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item item active">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="First slide">
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Second slide">
    </div>
    <div class="carousel-item item">
      <img class="d-block w-100" src="https://via.placeholder.com/500x300" alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
<script>
  var totalItems = $('.item').length;
  var currentIndex = $('div.item.active').index() + 1;

  var down_index;
  $('.num').html('' + currentIndex + '/' + totalItems + '');

  $(".next").click(function() {
    currentIndex_active = $('div.item.active').index() + 2;
    if (totalItems >= currentIndex_active) {
      down_index = $('div.item.active').index() + 2;
      $('.num').html('' + currentIndex_active + '/' + totalItems + '');
    }
  });

  $(".prev").click(function() {
    down_index = down_index - 1;
    if (down_index >= 1) {
      $('.num').html('' + down_index + '/' + totalItems + '');
    }
  });
</script>

答案 1 :(得分:0)

// this is simple slideshow with js     
<!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    * {box-sizing: border-box}
    body {font-family: Verdana, sans-serif; margin:0}
    .mySlides {display: none}
    img {vertical-align: middle;}

    /* Slideshow container */
    .slideshow-container {
      max-width: 1000px;
      position: relative;
      margin: auto;
    }

    /* Next & previous buttons */
    .prev, .next {
      cursor: pointer;
      position: absolute;
      top: 50%;
      width: auto;
      padding: 16px;
      margin-top: -22px;
      color: white;
      font-weight: bold;
      font-size: 18px;
      transition: 0.6s ease;
      border-radius: 0 3px 3px 0;
      user-select: none;
    }

    /* Position the "next button" to the right */
    .next {
      right: 0;
      border-radius: 3px 0 0 3px;
    }

    /* On hover, add a black background color with a little bit see-through */
    .prev:hover, .next:hover {
      background-color: rgba(0,0,0,0.8);
    }

    /* Caption text */
    .text {
      color: #f2f2f2;
      font-size: 15px;
      padding: 8px 12px;
      position: absolute;
      bottom: 8px;
      width: 100%;
      text-align: center;
    }

    /* Number text (1/3 etc) */
    .numbertext {
      color: #f2f2f2;
      font-size: 12px;
      padding: 8px 12px;
      position: absolute;
      top: 0;
    }

    /* The dots/bullets/indicators */
    .dot {
      cursor: pointer;
      height: 15px;
      width: 15px;
      margin: 0 2px;
      background-color: #bbb;
      border-radius: 50%;
      display: inline-block;
      transition: background-color 0.6s ease;
    }

    .active, .dot:hover {
      background-color: #717171;
    }

    /* Fading animation */
    .fade {
      -webkit-animation-name: fade;
      -webkit-animation-duration: 1.5s;
      animation-name: fade;
      animation-duration: 1.5s;
    }

    @-webkit-keyframes fade {
      from {opacity: .4} 
      to {opacity: 1}
    }

    @keyframes fade {
      from {opacity: .4} 
      to {opacity: 1}
    }

    /* On smaller screens, decrease text size */
    @media only screen and (max-width: 300px) {
      .prev, .next,.text {font-size: 11px}
    }
    </style>
    </head>
    <body>

    <div class="slideshow-container">

    <div class="mySlides fade">
      <div class="numbertext">1 / 3</div>
      <img src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width:100%">
      <div class="text">Caption Text</div>
    </div>

    <div class="mySlides fade">
      <div class="numbertext">2 / 3</div>
      <img src="https://www.w3schools.com/howto/img_snow_wide.jpg" style="width:100%">
      <div class="text">Caption Two</div>
    </div>

    <div class="mySlides fade">
      <div class="numbertext">3 / 3</div>
      <img src="https://www.w3schools.com/howto/img_snow_wide.jpg" style="width:100%">
      <div class="text">Caption Three</div>
    </div>
    </div>
    <br>

    <div style="text-align:center">
      <span class="dot" onclick="currentSlide(1)"></span> 
      <span class="dot" onclick="currentSlide(2)"></span> 
      <span class="dot" onclick="currentSlide(3)"></span> 
    </div>

    <script>
    var slideIndex = 1;
    showSlides(slideIndex);

    function plusSlides(n) {
      showSlides(slideIndex += n);
    }

    function currentSlide(n) {
      showSlides(slideIndex = n);
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("dot");
      if (n > slides.length) {slideIndex = 1}    
      if (n < 1) {slideIndex = slides.length}
      for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";  
      }
      for (i = 0; i < dots.length; i++) {
          dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex-1].style.display = "block";  
      dots[slideIndex-1].className += " active";
    }

    setInterval(function(){ plusSlides(1); }, 3000);
    </script>

    </body>
    </html> 

答案 2 :(得分:0)

检查我的答案,我添加了评论以更好地理解。

        //add all slides elements in array
        let slidesArr = $('.slide');
        //console.log(slidesArr);
        //console.log(slidesArr.length);
        
        //check before scroll for .slide that has active class
        //and show it to the user
        $.each(slidesArr, function(index, item) {
            if( $(item).hasClass('active')){
                $('.slide-num').html("<span>Slider no."+ (index+1) +"/"+slidesArr.length+" slide:"+item.id+"</span>");
            }
        });

       //scroll event
        $(window).scroll(function(){
            let scrolling = $(this);
            $.each(slidesArr, function(index, item) {
                let currentIndex = index + 1;
                
                //find each slide using offsetTop value
                //if the scrolling value is greater than the current slide offsetTop value select it as active
                if(scrolling.scrollTop() >= item.offsetTop){
                    //remove active class from all siblings
                    $(item).siblings().removeClass('active');
                    //add active class to the current slide
                    $(item).addClass('active');
                }

                if($(item).hasClass('active')){
                    $('.slide-num').html("<span>Slider no."+currentIndex+"/"+slidesArr.length+" slide:"+item.id+"</span>");
                }
            });

        });
body{height:1000px; }
 .slide-num{ position: fixed; top:50px;right:100px;border:1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slide-container">
        <div id="slide1" class="slide active">
          <h3>This is Slide 1</h3>
      
          <p>Some content for slide 1</p>
        </div>
      
        <div id="slide2" class="slide">
          <h3>This is Slide 2</h3>
      
          <p>Some content for slide 2</p>
        </div>
      
        <div id="slide3" class="slide">
          <h3>This is Slide 3</h3>
      
          <p>Some content for slide 3</p>
        </div>
      
        <div id="slide4" class="slide">
          <h3>This is Slide 4</h3>
      
          <p>Some content for slide 4</p>
        </div>

        <div class="slide-num"></div>
      </div>

答案 3 :(得分:0)

最简单的方法是处理任何滑动事件,检查哪个“ slide”元素具有“ active”类并找到其索引。

伪代码

function slidehandler () { // Make sure following code runs when slide changes
   console.log( "current index - " + $(".slide.active").index() );
   console.log( "Total slides - " + $(".slide").length );
}