如何让Twitter Bootstrap的Scrollspy插件与LazyLoad一起使用

时间:2013-04-23 17:45:00

标签: twitter-bootstrap lazy-loading scrollspy

我有很长的Div。有些有图像,有些有文字。我有Scrollspy附加到导航栏,当我向下滚动Div列表时会突出显示。

因为有很多图片,我也安装了LazyLoad

我遇到的挑战是,对于带图像的Div,看起来lazyload导致scrollspy不能正确读取Div的高度。这意味着在当前div完成滚动之前,scrollspy会突出显示下一个div的导航。

以下是我所拥有的代码的简化版本:

    <body>

    <ul class="nav nav-list bs-docs-sidenav ">
      <li><a href="#one">One</a></li>
      <li><a href="#two">Two</a></li>
      <li><a href="#three">Three</a></li>
    </ul>


    <div id="one">
      text
      text
      text
    </div>

    <div id="two">
      <p>
      <img class="lazy" src="images/loading.gif" data-original="images/two.png"  width="600" height="400" >
      <noscript><img src="images/two.png" width="600" height="400" ></noscript>
      </p>
       <p>
      <img class="lazy" src="images/loading.gif" data-original="images/two.png"  width="600" height="400" >
      <noscript><img src="images/two.png" width="600" height="400" ></noscript>
      </p>
    </div>

    <div id="three">
      text
      text
      text
    </div>



    <!-- bootstrap activations -->
    <script type="text/javascript"> 
        $('body').scrollspy()
    </script>

    <!-- lazy load -->
    <script src="scripts/jquery.lazyload.min.js" type="text/javascript"></script>
    <script type="text/javascript"> 
        $("img.lazy").show().lazyload({ 
            threshold : 100,
            effect : "fadeIn",
        }); 
    </script> 

    </body>

...所以在上面的代码中,当用户仍然滚动浏览包含图像的“Two”时,导航栏中的“Three”会突出显示。我相信我可能不得不对Scrollspy对DOM的“刷新”做些什么,但不清楚如何做到这一点或是否能解决问题:

    $('[data-spy="scroll"]').each(function () {
      var $spy = $(this).scrollspy('refresh')
    });

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这将在加载图像时调用refresh。

    <script type="text/javascript"> 
        $("img.lazy").show().lazyload({ 
            threshold : 100,
            effect : "fadeIn",
            load : function() {
             $('[data-spy="scroll"]').each(function () {
            var $spy = $(this).scrollspy('refresh')
            });
        }); 
    </script>