我想预装这4张图片。我试过这个:
<img src="img/1.jpg" style="display:none">
<img src="img/1a.jpg" style="display:none">
<img src="img/1b.jpg" style="display:none">
<img src="img/1c.jpg" style="display:none">
它不起作用,所以我试着这样做:
new Image().src = "img/1.jpg";
new Image().src = "img/1a.jpg";
new Image().src = "img/1b.jpg";
new Image().src = "img/1c.jpg";
JS方法处理的是后台,而不是这些。
最佳答案
尝试利用$.Deferred()
,.queue()
var images = ["http://lorempixel.com/1200/800/cats/"
, "http://lorempixel.com/1200/800/nature/"
, "http://lorempixel.com/1200/800/animals/"
, "http://lorempixel.com/1200/800/technics/"
];
// do stuff when image loaded
var loadImage = function loadImage(elem) {
return $(elem).fadeTo(500, "1.0", "linear");
};
// load images
var loadImages = function loadImages(urls, image, complete) {
// `this` : `document`
urls.forEach(function(imageSrc, i) {
var img = new Image;
var dfd = new $.Deferred();
// return `this` : `document`
dfd.then(function(ready) {
loadImage(ready);
return this
}, function(error) {
console.log(error)
})
.always(function() {
console.log(complete, urls.length);
return urls.length === complete
? $(this)
.data("complete", complete + " images loaded")
.dequeue("images") // when all images loaded
: this
});
// log errors
img.onerror = dfd.reject;
img.onload = function(e) {
complete = this.complete ? ++complete : complete;
dfd.resolveWith(document, [
image.eq(i).prop("src", this.src)
]
);
};
img.src = imageSrc
});
// return `this` : `document`
return this
};
$(window).load(function() {
// init `loadImages`
var complete = 0;
// call `loadImages`,
// `this` context : `document`
loadImages.call(document, images, $(".image"), complete)
});
$(document).ready(function() {
// notify when all images loaded
$(this).queue("images", function() {
console.log($(this).data())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<!-- note , `src` attribute not included -->
<img class="image" style="opacity:0.0" alt="1">
<img class="image" style="opacity:0.0" alt="1a">
<img class="image" style="opacity:0.0" alt="1b">
<img class="image" style="opacity:0.0" alt="1c">
关于javascript - 以HTML预加载图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29044852/