Unsorted list: load images or divs on demand

2019-07-28 03:45发布

问题:

I made a horizontal slider using iScroll.

I want to show a lot of images (or divs), and I added those images like this:

<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>

But it gets a lot of time to load every image (instead of images I'm going to use images map or divs).

How can I do that load images on demand? When user swipes to left, I want to load the next image.

回答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();
});

You might as well put most of that CSS in a class that affects the elements so you don't have to add it inline to each element:

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%;
}