Unsorted list: load images or divs on demand

ε祈祈猫儿з 提交于 2020-01-15 11:25:11

问题


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


来源:https://stackoverflow.com/questions/9810515/unsorted-list-load-images-or-divs-on-demand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!