Изменение переменной на основе точек останова

#javascript #jquery

#javascript #jquery

Вопрос:

Возможно ли изменить переменную на основе точек останова?

Переменная сначала устанавливается в этом скрипте

     $('#carousel-example').on('slide.bs.carousel', function (e) {
    /*
        CC 2.0 License Iatek LLC 2018 - Attribution required
    */
    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemsPerSlide = 5;
    var totalItems = $('.carousel-item').length;
 
    if (idx >= totalItems-(itemsPerSlide-1)) {
        var it = itemsPerSlide - (totalItems - idx);
        for (var i=0; i<it; i  ) {
            // append slides to end
            if (e.direction=="left") {
                $('.carousel-item').eq(i).appendTo('.carousel-inner');
            }
            else {
                $('.carousel-item').eq(0).appendTo('.carousel-inner');
            }
        }
    }
});
  

И я пытаюсь изменить переменные, поместив скрипт в тело … это, вероятно, преступно или даже невозможно, но я не программист, лол

 $(document).ready(function(){

    var bodyWidth = $('body').width(); 

    if(bodyWidth > 320 amp;amp; bodyWidth < 400) {
        var totalItems = $(‘.carousel-item’).length;
    var itemsPerSlide = totalItems – 3;
    }

    if(bodyWidth > 768 amp;amp; bodyWidth < 1024) {
        var itemsPerSlide = 5;
    var totalItems = $('.carousel-item').length;
    }

    if(bodyWidth > 1224) {
        var itemsPerSlide = 5;
    var totalItems = $('.carousel-item').length; 
    }

});
  

Ответ №1:

Я заметил, что вы используете bootstraps carousel, и вы хотите контролировать, сколько слайдов на каждой отзывчивой точке останова.

Я постоянно использую bootstrap, и когда мне когда-либо понадобится карусель, я использую скользкий слайдер Кена Уилерса. Супер простой в использовании, использует jQuery, который у вас уже есть, и обладает потрясающей адаптивной функциональностью точки останова, а также другими интересными опциями.

Посмотрите этот пример и посмотрите Мои комментарии в коде…

 // bootstrap default break points constant variable object
const breakpoint = {

  // Small screen / phone
  sm: 576,

  // Medium screen / tablet
  md: 768,

  // Large screen / desktop
  lg: 992,

  // Extra large screen / wide desktop
  xl: 1200

};

// carousel example slick slider
$('#carousel-example').slick({
  
  // settings from now are mobile first
  autoplay: true,
  autoplaySpeed: 2000,
  draggable: true,
  infinite: true,
  dots: true,
  arrows: false,
  speed: 1000,
  mobileFirst: true,
  
  // 2 slides to show/scroll (on mobile)
  slidesToShow: 2,
  slidesToScroll: 2,
  
  // begin responsive settings
  responsive: [{
  
      // overrides or new settings at breakpoint sm and up
      breakpoint: breakpoint.sm,
      settings: {

        // show carousel controls (override) 
        arrows: true,
        
        // 3 slides to show/scroll (overrides)
        slidesToShow: 3,
        slidesToScroll: 3
      }
    },
    {
    
      // overrides or new settings at breakpoint md and up
      breakpoint: breakpoint.md,
      settings: {
      
        // show carousel controls (override) 
        arrows: true,
        
        // 4 slides to show/scroll (overrides) 
        slidesToShow: 4,
        slidesToScroll: 4
      }
    },
    {
    
      // overrides or new settings at breakpoint lg and up
      breakpoint: breakpoint.lg,
      settings: {
      
        // show carousel controls (override) 
        arrows: true,
        
        // 5 slides to show/scroll (overrides) 
        slidesToShow: 5,
        slidesToScroll: 5
      }
    },
    {
    
      // overrides or new settings at breakpoint xl (add more custom breakpoints too breakpoint constant variable
      breakpoint: breakpoint.xl,
      settings: {
      
        // show carousel controls (override) 
        arrows: true,
        
        // 6 slides to show/scroll (overrides) 
        slidesToShow: 6,
        slidesToScroll: 6
      }
    }
  ]
});  
 /* carousel example css to be hidden until initialized */

#carousel-example {
  opacity: 0;
  transition: opacity .5s ease;
  height: 0;
  overflow: hidden;
}

#carousel-example.slick-initialized {
  opacity: 1;
  height: auto;
  overflow: initial;
}


/* carousel example css to emulate boostraps grid so each slide behaves like a column inside a row, but the slide "column" widths are handled by slicks responsive settings */

#carousel-example .slick-list {
  margin-left: -15px;
  margin-right: -15px;
}

#carousel-example .slick-list:before,
#carousel-example .slick-list:after {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  background: red;
  width: 15px;
  z-index: 10;
  background: #fff; /* set this to your page background color */
}

#carousel-example .slick-list:before {
  left: 0;
  /* background: linear-gradient(-90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%); */
}

#carousel-example .slick-list:after {
  right: 0;
  /* background: linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%); */
}

#carousel-example .slick-slide {
  padding-right: 15px;
  padding-left: 15px;
}

#carousel-example .slick-slide:focus {
  outline: none;
}


/* carousel example css to emulate boostrap carousel controls */

#carousel-example .slick-arrow {
  position: absolute;
  top: 50%;
  display: block;
  width: 20px;
  height: 20px;
  background: transparent no-repeat 50%/100% 100%;
  overflow: hidden;
  text-indent: 1000px;
  border: none;
}

#carousel-example .slick-arrow:focus {
  outline: none;
}

#carousel-example .slick-prev {
  left: -15px;
  transform: translate(-100%, -50%);
  background-image: url("data:image/svg xml,");
}

#carousel-example .slick-next {
  right: -15px;
  transform: translate(100%, -50%);
  background-image: url("data:image/svg xml,");
}


/* carousel example css to emulate bootstrap carousels indicators */

#carousel-example .slick-dots {
  position: relative;
  z-index: 15;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-pack: center;
  justify-content: center;
  padding-left: 0;
  margin-right: 15%;
  margin-left: 15%;
  margin-top: 15px;
  list-style: none;
}

#carousel-example .slick-dots LI {
  box-sizing: content-box;
  -ms-flex: 0 1 auto;
  flex: 0 1 auto;
  width: 30px;
  height: 3px;
  margin-right: 3px;
  margin-left: 3px;
  text-indent: -999px;
  cursor: pointer;
  background-color: #212529;
  background-clip: padding-box;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  opacity: .5;
  transition: opacity .6s ease;
}

#carousel-example .slick-dots LI.slick-active,
#carousel-example .slick-dots LI:hover {
  opacity: 1;
}

#carousel-example .slick-dots LI>BUTTON {
  display: none;
}


/* fix for demo overflow horizontal scrolling */

BODY {
  overflow-x: hidden;
}  
 <!-- bootstrap css -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">

<!-- slick css -->
<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet" />

<!-- bootstrap container for demo -->
<div class="container py-3">

  <!-- carousel example slider -->
  <div id="carousel-example">

    <div class="slide">
      <div class="card">
        <img src="https://i.imgur.com/q5Y5RCH.png" class="card-img-top" />
        <div class="card-body">
          <h5 class="card-title">Article title</h5>
          <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris...</p>
          <a href="#" class="btn btn-primary">Read more</a>
        </div>
      </div>
    </div>

    <div class="slide">
      <div class="card">
        <img src="https://i.imgur.com/8HjXPXD.png" class="card-img-top" />
        <div class="card-body">
          <h5 class="card-title">Article title</h5>
          <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris...</p>
          <a href="#" class="btn btn-primary">Read more</a>
        </div>
      </div>
    </div>

    <div class="slide">
      <div class="card">
        <img src="https://i.imgur.com/vUDcfcy.png" class="card-img-top" />
        <div class="card-body">
          <h5 class="card-title">Article title</h5>
          <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris...</p>
          <a href="#" class="btn btn-primary">Read more</a>
        </div>
      </div>
    </div>

    <div class="slide">
      <div class="card">
        <img src="https://i.imgur.com/okTDHas.png" class="card-img-top" />
        <div class="card-body">
          <h5 class="card-title">Article title</h5>
          <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris...</p>
          <a href="#" class="btn btn-primary">Read more</a>
        </div>
      </div>
    </div>

    <div class="slide">
      <div class="card">
        <img src="https://i.imgur.com/x7ZYW4i.png" class="card-img-top" />
        <div class="card-body">
          <h5 class="card-title">Article title</h5>
          <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris...</p>
          <a href="#" class="btn btn-primary">Read more</a>
        </div>
      </div>
    </div>

    <div class="slide">
      <div class="card">
        <img src="https://i.imgur.com/EYTCssm.png" class="card-img-top" />
        <div class="card-body">
          <h5 class="card-title">Article title</h5>
          <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris...</p>
          <a href="#" class="btn btn-primary">Read more</a>
        </div>
      </div>
    </div>

  </div>
  
</div>

<!-- jQuery and bootstrap 4 js bundle w/ popper.js -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- slick jQuery min -->
<script src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>