滑块不时不起作用

时间:2017-10-27 14:47:34

标签: javascript jquery wordpress

我在一个woocommerce网站上添加了一个滑块滑块。 滑块并不总是适用于可变项目,大多数情况下它只显示图像列表。

原因可能是在我初始化滑块之前页面没有完全渲染。我已经尝试初始化$(window).on('load', function(){})内的滑块,但它没有帮助。

有什么建议吗?

可变项目: https://escooter-shop.at/shop/e-scooter/e-scooter-easy-rider/

简单项目(效果很好): https://escooter-shop.at/shop/e-scooter/e-scooter-inmotion-l6/

代码:

$(window).on('load', function(){
  console.log('Window on.load reached')
  $('.single-product .thumbnails a').wrap('<div class="swiper-slide" />');
  $('.swiper-slide').wrapAll( '<div class="swiper-wrapper"></div>');
  $('.swiper-wrapper').wrapAll( '<div class="swiper-container"></div>');

  $('<div class="swiper-button-prev"></div>').insertAfter( $('.swiper-wrapper'));
  $('<div class="swiper-button-next"></div>').insertAfter( $('.swiper-button-prev'));

  var mySwiper = new Swiper ('.swiper-container', {
    direction: 'horizontal',
    loop: true,
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    slidesPerView: 3,
    spaceBetween: 40,
    breakpoints: {
      480: {
        slidesPerView: 2
      },
    }
  });
});

1 个答案:

答案 0 :(得分:0)

我的解决方案是在4秒后重新初始化滑块。这足以使可变产品页面完全加载。 现在我有简单的项目加载滑块和变量产品,并在4秒后添加滑块。

  // Initializing the product images slider
  var sliderInit = function(){
    $('.single-product .thumbnails a').wrap('<div class="swiper-slide"/>');
    $('.swiper-slide').wrapAll( '<div class="swiper-wrapper"></div>');
    $('.swiper-wrapper').wrapAll( '<div class="swiper-container"></div>');

    $('<div class="swiper-button-prev"></div>').insertAfter( $('.swiper-wrapper'));
    $('<div class="swiper-button-next"></div>').insertAfter( $('.swiper-button-prev'));

    var mySwiper = new Swiper ('.swiper-container', {
      direction: 'horizontal',
      loop: true,
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
      slidesPerView: 3,
      spaceBetween: 40,
      breakpoints: {
        480: {
          slidesPerView: 2
        },
      }
    });
  };

  // reinitializing the product images slider for variable products
  setTimeout(function(){ 
    if($('.thumbnails .swiper-container').length < 1 ){
      sliderInit();
    }
  }, 4000);