编程语言
首页 > 编程语言> > 使用javascript和for循环在页面加载后预加载图像

使用javascript和for循环在页面加载后预加载图像

作者:互联网

我目前正在创建网页照相馆.页面加载后,我想用Javascript预加载大量图像.可以在循环中使用HTML链接,而不是在列表中列出非常长的HTML链接吗?请看下面的代码.对于我在for循环中做错的任何有用的见解,将不胜感激!谢谢!!

<script type="text/javascript">
    function preloader() {
        var images = new Array()
        function preload() {
            for (i = 0; i < preload.arguments.length; i++) {
                images[i] = new Image()
                images[i].src = preload.arguments[i]
            }
        }
        preload(
            var i=1;
            "http://example.com/images/gallery/elephants-" + for (i=1;i<=5;i++) {document.write(i);} + ".jpg",
            "http://example.com/images/gallery/penguins-" + for (i=1;i<=2;i++) {document.write(i);} + ".png"
        )
    }

    function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            }
        }
    }
    addLoadEvent(preloader);
</script>

我遇到问题的部分是preload()部分中的for循环. preload()部分应输出/执行以下操作:

preload(
    "http://example.com/images/gallery/elephants-1.jpg",
    "http://example.com/images/gallery/elephants-2.jpg",
    "http://example.com/images/gallery/elephants-3.jpg",
    "http://example.com/images/gallery/elephants-4.jpg",
    "http://example.com/images/gallery/elephants-5.jpg",
    "http://example.com/images/gallery/penguins-1.png",
    "http://example.com/images/gallery/penguins-2.png"
)

解决方法:

您不能将字符串和循环连接在一起.您必须使用循环和push方法构建字符串数组:

var i, urls = [];
for(i = 1; i <= 5; i++)
    urls.push('http://example.com/images/gallery/elephants-' + i + '.jpg');
for(i = 1; i <= 2; i++)
    urls.push('http://example.com/images/gallery/penguins-' + i + '.jpg');

然后使用apply调用preload函数并将该数组作为参数传递:

preload.apply(null, urls);

因此,您的整个预加载器功能变为:

function preloader() {
    var images = new Array()
    function preload() {
        for (i = 0; i < preload.arguments.length; i++) {
            images[i] = new Image()
            images[i].src = preload.arguments[i]
        }
    }

    var i, urls = [];
    for(i = 1; i <= 5; i++)
        urls.push('http://example.com/images/gallery/elephants-' + i + '.jpg');
    for(i = 1; i <= 2; i++)
        urls.push('http://example.com/images/gallery/penguins-' + i + '.jpg');

    preload.apply(null, urls);
}

标签:loops,for-loop,image,preload,javascript
来源: https://codeday.me/bug/20191201/2080266.html