我认为作者的意思是在代码中额外加入对
whileScrolling
事件的钩子,像这样:
(function($){
$(window).load(function(){
$("#content_1").mCustomScrollbar({
scrollButtons:{
enable:true
},
callbacks:{
whileScrolling:function(){ WhileScrolling(); }
}
});
function WhileScrolling(){
$("img.lazy").lazyload();
}
});
})(jQuery);
HTML容器如下所示:
<div id="content_1" class="content">
<p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
<p>
<img class="lazy img-responsive" data-original="/img/bmw_m1_hood.jpg" width="765" height="574" alt="BMW M1 Hood"><br/>
<img class="lazy img-responsive" data-original="/img/bmw_m1_side.jpg" width="765" height="574" alt="BMW M1 Side"><br/>
<img class="lazy img-responsive" data-original="/img/viper_1.jpg" width="765" height="574" alt="Viper 1"><br/>
<img class="lazy img-responsive" data-original="/img/viper_corner.jpg" width="765" height="574" alt="Viper Corner"><br/>
<img class="lazy img-responsive" data-original="/img/bmw_m3_gt.jpg" width="765" height="574" alt="BMW M3 GT"><br/>
<img class="lazy img-responsive" data-original="/img/corvette_pitstop.jpg" width="765" height="574" alt="Corvette Pitstop"><br/>
</p>
<p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti. </p>
<p>Consectetur adipiscing elit. Nulla consectetur libero consectetur quam consequat nec tincidunt massa feugiat. Donec egestas mi turpis. Fusce adipiscing dui eu metus gravida vel facilisis ligula iaculis. Cras a rhoncus massa. Donec sed purus eget nunc placerat consequat.</p>
<p>Cras venenatis condimentum nibh a mollis. Duis id sapien nibh. Vivamus porttitor, felis quis blandit tincidunt, erat magna scelerisque urna, a faucibus erat nisl eget nisl. Aliquam consequat turpis id velit egestas a posuere orci semper. Mauris suscipit erat quis urna adipiscing ultricies. In hac habitasse platea dictumst. Nulla scelerisque lorem quis dui sagittis egestas.</p>
<p>Etiam sed massa felis, aliquam pellentesque est.</p>
<p>the end.</p>
</div>
为了减少滚动时
lazyload()
的数量,我们可以使用例如
mcs.top
属性来获取滚动内容的顶部位置(像素):
function WhileScrolling()
{
// Debug:
// console.log( 'top: ' + mcs.top );
// Run lazyload in 10 pixel steps (adjust to your needs)
if( 0 == mcs.top % 10 )
{
// Run lazyload on the "div#conent_1" box:
$("#content_1 img.lazy").lazyload();
// Debug:
//console.log( 'lazyload - mcs.top: ' + mcs.top );
}
}
在这里,我们限制了懒加载选择器,这样我们就不必查找整个DOM树中的所有图像。
我注意到在Internet Explorer 11中,mcs.top
可以是浮点数,但在Chrome中它总是整数。
因此,我们可以使用Math.floor()
对其进行向下取整。
为了进一步减少lazyload调用,我们可以将mcs.top
与其先前的值进行比较:
var mcsTopPrev = 0;
var mcsTop = 0;
function WhileScrolling()
{
mcsTop = Math.floor( mcs.top );
if( mcsTop != mcsTopPrev )
{
if( 0 == mcsTop % 10 )
{
$("#cphContent_lReferences img.lazy").lazyload();
}
}
mcsTopPrev = mcsTop;
}