【问题标题】:How do I add loading indicator to an <img>?如何将加载指示器添加到 <img>?
【发布时间】:2015-09-28 13:54:54
【问题描述】:

我的项目中有以下 HTML。

<div class="container" id="crop">
    <img id="timage" src="http://example.com/color/style/etc/" alt="timages" />

我还有以下 javascript:

$(window).load(function () {
$("#slider").change(function update() {
    sVal = $(this).val();
    if (sVal == 2) {
            $('#timage').prop('src',"http://example.com/" +
            tForm +
            "color.blahblah" + 
            itemCode + 
            "therest_ofthe_URL");}

    sVal = $(this).val();
    if (sVal == 3) {
            $('#timage').prop('src',"http://example.com/" +
            tForm +
            "color.blahblah" + 
            itemCode + 
            "therest_ofthe_URL");}
            );}

当滑块值达到一定数字时,用字符串替换图像效果很好。问题是,图像是在幕后的后端创建的,并且需要相当长的时间才能准备好。与此同时,您只是盯着原始图像想知道滑块是否做了任何事情。

如何添加加载指示器以让人们知道图像即将更改?

【问题讨论】:

    标签: javascript jquery html loading gif


    【解决方案1】:

    首先,在您想要的位置放置一个加载指示器。例如,您可以用旋转的 gif 替换 #timage。然后使用此代码开始新的图像加载:

    var img = new Image();
    img.onload = function () {
        $('#timage').prop('src', img.src);
    }
    img.src = '/image/to/load/here';
    

    当您的新图像已从服务器检索并加载后,该函数将被执行。由于它已经缓存在客户端上,一旦设置了#timage 的 src,它应该会立即加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 2023-03-21
      • 2012-03-12
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      相关资源
      最近更新 更多