javascript - 用较大的图像替换较小的图像(在加载较大的图像后)

标签 javascript css html

我有一些 super 英雄的图片。这些在 div 中,连同更大的天文物体图像。这些较大的图像需要一段时间才能加载。我希望天文图像在加载后替换 super 英雄图像。

这是我目前拥有的:https://jsfiddle.net/vmpfc1/5typ7pnp/1/

HTML:

<body>
  <div class="image-wrapper">
    <div class="pix"style="background: url('http://baltimorepostexaminer.com/wp-content/uploads/2012/07/spider-man2_pole_4681.jpg'); height:200px;width:200px;">
    </div>
    <div class="true-image" style="background: url('http://m1.i.pbase.com/o9/27/876727/1/151851961.JlvdQ9xW.GreatCarinaKeyholeandRedHoodNebulae3454x2566pixelsimproved3.jpg')"></div>
    </div>

  <div class="image-wrapper">
    <div class="pix"style="background: url('https://upload.wikimedia.org/wikipedia/en/7/75/Comic_Art_-_Batman_by_Jim_Lee_%282002%29.png'); height:200px;width:200px;">
    </div>
    <div class="true-image" style="background:url(' https://www.nasa.gov/sites/default/files/706439main_20121113_m6triptych_0.jpg')"></div>
  </div>

</body>

js:

setTimeout(function () {
    $('.true-image').attr('style').on('load', function () {
        $('.pix')({
            'background-image': 'url(' + $(this).attr('src') + ')'
        });
    });
}, 0);

CSS:

.true-image {
    display : none;
}

我是一个 javascript 新手 -- 有什么好的方法可以让更大的空间图像替换 super 英雄占位符吗?

在 HTML5 中有更简单的方法吗?

最佳答案

编辑答案以反射(reflect)变化:

<div style="background-image: url('https://i.imgur.com/sOcRl3M.jpg'); height:400px;width:400px" rel="https://i.imgur.com/xr7CRQo.jpg">
</div>

<div style="background-image: url('https://i.imgur.com/1m0NwgN.png'); height:400px;width:400px" rel="https://i.imgur.com/nlFPkc4.jpg">
</div>

然后您可以让 jQuery 循环遍历所有具有 rel 属性的图像。 2 张或 2,000 张图像都没有关系。

$('div[rel]').each(function() {
  var rel = $(this).attr('rel');
  var self = $(this);
  var img = new Image();
  $(img).load(rel, '', function() {
    self.css('background-image', 'url('+rel+')');
  });
});

你可以看到它在这里工作:https://jsfiddle.net/83zLumuk/4/

关于javascript - 用较大的图像替换较小的图像(在加载较大的图像后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35377606/

相关文章:

javascript - 无法渲染 Web 组件

css - 悬停在谷歌浏览器上时菜单消失 - 适用于 IE 和 firefox

angularjs - Videogular - 如何在 div ng-click 上播放给定的视频文件?

JavaScript 按类名获取所有元素,同时排除特定类?

javascript - string.endswith ("") 在 IE 中不起作用(不确定如何使用 Polyfill)

javascript - 模式弹出窗口未显示在另一个模式弹出窗口之上

javascript - 幻灯片上的图像向下跳跃

html - CSS Layout对齐问题

javascript - 悬停时的jquery动画边框

css - div 100% 高度在屏幕中央