我有一些 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/