2016-02-13 51 views
0

我有几张超级英雄的图像。这些都与天文物体的更大的图像一起呈现。这些较大的图像需要一段时间才能加载。我希望天文图像在加载后替换超级英雄图像。用较大的图像替换较小的图像(在较大图像加载后)

这是我到目前为止有: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新手 - 有一个十二月如何让更大的空间图像取代超级英雄占位符?

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

+0

延迟加载 - https://css-tricks.com/snippets/javascript/lazy-loading-images/ – CodeRomeos

回答

1

编辑答案,以反映变化:

<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> 

然后你就可以通过具有rel属性的所有图像有jQuery的循环。 2或2000张图片,没关系。

$('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/

+0

感谢一大堆!由于原因,我需要的结构是像背景图像的div在这个小提琴的HTML:https://jsfiddle.net/vmpfc1/83zLumuk/2/ 你知道如何让js在这种情况下工作? – vmpfc1

相关问题