javascript预加载器/进度/百分比 [英] javascript preloader/progress/percentage

查看:96
本文介绍了javascript预加载器/进度/百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到有关如何制作javascript(或jquery)进度条的任何有用信息,其中包含告诉您百分比的文本。

I'm having trouble finding any good information on how to make a javascript(or jquery) progress bar WITH text that tells you the percentage.

我不知道我想要一个插件,我只是想知道它是如何工作的,这样我就可以根据我的需要进行调整。如何预加载图像并获取预加载图像数量的变量。另外,如何根据已加载的图像数量更改html / css和/或调用函数?

I don't want a plug in, I just want to know how it works so that I can adapt it to what I need. How do you preload images and get a variable for the number of images that are preloaded. Also, how do you change html/css and-or call a function, based on the number of images that are loaded already?

推荐答案

< img> 元素有一个 onload 事件,一旦图像完全加载就会触发。因此,在js中,您可以跟踪已加载的图像数量与使用此事件的剩余数量。

<img> elements have an onload event that fires once the image has fully loaded. Therefore, in js you can keep track of the number of images that have loaded vs the number remaining using this event.

图像也有相应的 onerror onabort 在图像无法加载或下载中止时触发的事件(由用户按下x按钮)。您还需要跟踪它们以及 onload 事件,以便正确跟踪图像加载。

Images also have corresponding onerror and onabort events that fire when the image fails to load or the download have been aborted (by the user pressing the 'x' button). You also need to keep track of them along with the onload event to keep track of image loading properly.

纯js中的一个简单示例:

A simple example in pure js:

var img_to_load = [ '/img/1.jpg', '/img/2.jpg' ];
var loaded_images = 0;

for (var i=0; i<img_to_load.length; i++) {
    var img = document.createElement('img');
    img.src = img_to_load[i];
    img.style.display = 'hidden'; // don't display preloaded images
    img.onload = function () {
        loaded_images ++;
        if (loaded_images == img_to_load.length) {
            alert('done loading images');
        }
        else {
            alert((100*loaded_images/img_to_load.length) + '% loaded');
        }
    }
    document.body.appendChild(img);
}

上面的示例不处理 onerror onabort 为了清楚起见,现实代码也应该照顾它们。

The example above doesn't handle onerror or onabort for clarity but real world code should take care of them as well.

这篇关于javascript预加载器/进度/百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆