未排序列表:按需加载图像或div

时间:2012-03-21 18:19:29

标签: jquery css jquery-mobile slider iscroll4

我使用iScroll创建了一个水平滑块。

我想展示很多图像(或div),我添加了这样的图像:

<ul>
<li style="background: url(fotos/PabloskiMarzo2008.jpg) no-repeat;  background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; -webkit-background-size: 100%; -khtml-background-size: 100%;  "></li>
...
<ul>

但是它需要花费大量时间来加载每个图像(而不是图像我将使用图像映射或div)。

如何按需加载图片?当用户向左滑动时,我想加载下一张图像。

1 个答案:

答案 0 :(得分:1)

//setup list of images to lazy-load, also setup variable to store current index in the array
var listOfImages = ['fotos/zero.jpg', 'fotos/one.jpg', 'fotos/infinity.jpg'],
    imageIndex   = 0,
    myScroll     = new iScroll('my-element');

//bind to the swipeleft event on the list
$('ul').bind('swipeleft', function () {

    //append a new list-item to the list, using the `listOfImages` array to get the next source
    //notice the `++` that increments the `imageIndex` variable
    $(this).append($('li', { style : 'background: url(' + listOfImages[imageIndex++] + ') no-repeat;  background-size: 100%; -moz-background-size: 100%; -o-background-size: 100%; -webkit-background-size: 100%; -khtml-background-size: 100%;' }));

    //since the dimensions of your scroller have changed, you have to let iScroll know
    myScroll.refresh();
});

您可以将大部分CSS放在影响元素的类中,这样您就不必将其内联添加到每个元素中:

JS -

    $(this).append($('li', { style : 'background-image : url(' + listOfImages[imageIndex++] + ')' }));

CSS -

#my-element li {
    background-repeat       : no-repeat;
    background-size         : 100%;
    -moz-background-size    : 100%;
    -o-background-size      : 100%; 
    -webkit-background-size : 100%;
    -khtml-background-size  : 100%;
}
相关问题