[英]Getting portions of javascript to fire before entire function(s) finishes
I am changing a image via jQuery, but the image takes a few seconds to load and hence appears like the click did nothing, so I needed to input a temporary "loading" image to show the user that the image is loading. 我正在通过jQuery更改图像,但是该图像需要花费几秒钟的时间来加载,因此看起来就像单击操作一样,因此我需要输入一个临时的“正在加载”图像以向用户显示该图像正在加载。
However as I have experienced in the past JS doesn't really fire things as things happen, it waits until the full function is done before things happen; 但是,正如我过去所经历的那样,JS并不会在事情发生时真正触发事情,而是要等到完整功能完成后再进行事情。 I recall coming up with a solution in the past but I just can't remember what it was. 我记得过去曾提出过一个解决方案,但我只是不记得它是什么。
I have this which does each task, but the user never sees the loading image because it is replaced by the new image before the user even sees anything. 我有完成每个任务的程序,但是用户从未看到加载图像,因为在用户看到任何东西之前,它已被新图像替换。
function changeMainImage(image) {
// Set temporary loading image
jQuery('#main_image').attr('src', 'images/loading.jpeg');
// Set big image
var big_image = image + '-big.png'
// Update main image url
jQuery('#main_image').attr('src', big_image);
}
I have tried putting the below into a separate function: 我尝试将以下内容放入单独的函数中:
// Set temporary loading image
jQuery('#main_image').attr('src', 'images/loading.jpeg');
..and calling it before the other function like so.. ..并在其他函数之前调用它..
onclick="setLoadingIMage(); changeMainImage('images/ai');"
but that didn't change anything. 但这并没有改变任何东西。
Could anyone tell me what I need to do to achieve the effect I want? 谁能告诉我要达到我想要的效果我需要做什么?
<label id="label"> Loading </label>
<img src="src" id="image" style="display:none;"/>
JS: JS:
var image = document.getElementById('image');
var label = document.getElementById('label');
image.onload = function(){
image.style.display = "block";
label.style.display = "none";
}
Fiddle: http://jsfiddle.net/3x63F/ (the image is too big, so it may take several minutes to load) 小提琴: http : //jsfiddle.net/3x63F/ (图片太大,因此加载可能需要几分钟的时间)
This will display the loading.jpeg
until the image has been loaded. 这将显示loading.jpeg
直到图像已加载。
function changeMainImage(image) {
jQuery('#main_image').attr('src', 'images/loading.jpeg');
var img = new Image();
img.src = image + "-big.png";
img.onload = function( ) {
jQuery('#main_image').attr('src', img.src );
}
}
If the image is held in cache then img.onload
will fire immediately. 如果图像保留在缓存中,则img.onload
将立即触发。
Here is a trick I use for this: 这是我为此使用的一个技巧:
Hope this works for you. 希望这对您有用。 Also, you may choose an animated gif for loading image. 另外,您可以选择动画gif来加载图像。
Here is the tutorial of how to accomplish showing the spinner in the foreground while the image is loading in background 这是有关如何在背景加载图像时完成在前景中显示微调框的教程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.