【问题标题】:Simple jQuery Carousel Slide Counter简单的 jQuery 轮播幻灯片计数器
【发布时间】:2020-03-31 01:27:43
【问题描述】:

我的网站部分中有一个简单的基于文本的水平滑块,可以左右滚动,由鼠标滚动控制。我试图弄清楚如何显示幻灯片的当前索引和幻灯片总数。例如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 人,但我认为我可以试一试,事实证明它比看起来要难一些。

我们将不胜感激任何对正确方向的见解或推动。

【问题讨论】:

  • 最简单的方法是,在您的滚动事件处理程序中,检查哪个“幻灯片”元素具有“活动”类并找到它的索引。

标签: jquery html css carousel counter


【解决方案1】:

// 这是一个简单易用的带有索引的轮播滑块,希望这段代码对您的要求有所帮助

<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>

【讨论】:

  • 感谢您的回答,但是,我没有使用引导程序的轮播,也没有导航幻灯片的“点击”功能,它都是“基于滚动的”。所以我不确定如何将它应用到我的示例中?
  • 好的,请分享你的工作示例,以便我修复。下面我用js分享了简单的核心幻灯片
【解决方案2】:
// 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> 

【讨论】:

    【解决方案3】:

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

            //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>

    【讨论】:

      【解决方案4】:

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

      伪代码

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

      【讨论】:

      • 奇怪的是,幻灯片更改时两者都不会触发。我还不得不把它从函数中去掉,因为没有任何东西调用函数来返回任何结果。
      • @JasonRyan:能否请您包含更改幻灯片的代码?还是完整的代码?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 2016-11-01
      • 2012-11-22
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多