在窗口上重新加载bxSlider调整大小

时间:2016-07-19 08:36:00

标签: javascript reload bxslider

我在我的网站上使用bxSlider。滑块应在窗口大小调整时重新加载。使用代码我实际使用滑块是loadad加载和调整大小。但是滑块没有重新加载,而是第二次加载。所以我有2个加载的滑块。我只需要重新加载滑块而不是再次加载它。

$(window).on('load resize', function () {
    /* BX SLIDER */
    $('#bannerslider').bxSlider({
        captions: true
    }); 
});

1 个答案:

答案 0 :(得分:1)

使用bxSlider API中的2个回调:

  • onSliderResize()当触发调整大小事件时,reloadBX()将调用.reloadSlider,将当前索引存储在localStorage中并检索它以维持索引位置而不是重新加载后从头开始。

  • onSliderLoad()当触发加载事件时,checkBX()将检查bxSlider的高度,如果它被折叠(0px),它将调用redrawSlider()。这会以图形方式强制重置,直到成功强制bxSlider唤醒为止。

此代码段运行速度很快,因此我设置控制台以显示它正在运行。当然,请以全页模式查看它。如果由于某种原因导致代码段被破坏(有时会破坏),您可以在 Plunker

测试演示



<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>bxSlider Resize</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/bxslider/4.2.5/jquery.bxslider.css">
  <style>
    img {
      margin: 0 auto;
      display: block;
    }
    /* Ruleset makes img centered. */
  </style>
</head>

<body>
  <ul class='bx'>
    <li>
      <img src="http://placehold.it/640x480/000/fff?text=1">
    </li>
    <li>
      <img src="http://placehold.it/640x480/00f/fc0?text=2">
    </li>
    <li>
      <img src="http://placehold.it/640x480/8de/fa6?text=3">
    </li>
    <li>
      <img src="http://placehold.it/640x480/cb9/0ff?text=4">
    </li>
    <li>
      <img src="http://placehold.it/640x480/fff/000?text=5">
    </li>
  </ul>
  <input id='cache' type='hidden'>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/bxslider/4.2.5/jquery.bxslider.min.js"></script>
  <!-- The 3 console.logs facilitates debugging. 
//]  They are optional and are not essential for overall functioning.//-->
  <script>
    var bx = $('.bx').bxSlider({
      captions: true,
      // onResize 
      onSliderResize: reloadBX,
      // onLoad
      onSliderLoad: checkBX
    });

    /*
    Resize Callback 
    */ // Stores the current slide index.
    function reloadBX(idx) {
      localStorage.cache = idx;
      console.log('Reload on Slide: ' + idx);
      // Reloads slider, 
      ///goes back to the slide it was on before resize,
      ///removes the stored index.
      function inner(idx) {
        setTimeout(bx.reloadSlider, 0);
        var current = parseInt(idx, 10);
        console.log('RELOADED');
        bx.goToSlide(current);
        localStorage.removeItem("cache");
      }
    }

    /*
    Load Callback
    */ // If the slider height is collapsed, 
     /////invoke a repaint and stay on current index.
    function checkBX(idx) {
      var vp = $('.bx-viewport').height();
      console.log('View-port Height: ' + vp + 'px');
      while (vp <= 0) {
        bx.redrawSlider();
        console.log('REPAINT');
      }
 
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;