【问题标题】:HTML hidden image - how to download and size before revealing? [duplicate]HTML隐藏图像 - 如何在显示之前下载和调整大小? [复制]
【发布时间】:2013-01-09 07:47:02
【问题描述】:

可能重复:
JavaScript Preloading Images

我正在使用 JS 在页面加载后的某个时间设置 img.hidden=false。这会导致图像下载并调整 img 元素的大小 - 我想避免这种情况(我使用内联样式 width:2em 来调整图像大小)。其次,当我更改 img 源时,第二张图片下载时会有一点延迟。

如何在页面上显示之前下载我的图片...?

【问题讨论】:

标签: javascript html image


【解决方案1】:

先下载图片,然后触发动作,用jquery这样:

  var i = document.createElement('img'); // or new Image()
  // may be you need to set the element id...
  i.id = 'your id';
  // here handle on load event
  $(i).load(function() {

       // finally the new image is loaded, you can trigger your action
       $('#container').append($(this));

  });
  // This is the last step, set the url and start the image download.
  i.src = 'http://www.hostname.com/yourimage.jpg';

【讨论】:

    【解决方案2】:

    没有 jQuery(如果需要):

    var imageNode = new Image(); // or document.createElement('img');
    
    imageNode.onload = function(e) {
        // Code for appending to the DOM
        document.getElementById('container').appendChild(this);
    };
    
    imageNode.src = 'path/to/image.jpg';
    

    如果你的 img 标签已经存在,像这样:

    <img id='myimg' alt=''>
    

    在 JavaScript 中使用:

    var imageNode = document.getElementById('myimg');
    

    代替:

    var imageNode = new Image();
    

    请记住,代码需要在 img 标记之后或 DOM 准备好/加载时执行。否则代码执行时不存在

    【讨论】:

    • 我只是想知道如何在没有 jquery 的情况下做到这一点 :)
    • 如何将它绑定到我的 html 中的 标签?
    • 好的,我已经编辑了一点,以便更清楚地说明如何将它与现有的 img 标签一起使用。请检查它是否有任何帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2017-06-21
    • 2014-08-09
    • 2013-03-11
    相关资源
    最近更新 更多