我想在 body 标签上设置背景图像,然后运行一些代码 - 像这样:
$('body').css('background-image','http://picture.de/image.png').load(function() {
alert('Background image done loading');
// This doesn't work
});
如何确保背景图像已完全加载?
我想在 body 标签上设置背景图像,然后运行一些代码 - 像这样:
$('body').css('background-image','http://picture.de/image.png').load(function() {
alert('Background image done loading');
// This doesn't work
});
如何确保背景图像已完全加载?
试试这个:
$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
$(this).remove(); // prevent memory leaks as @benweet suggested
$('body').css('background-image', 'url(http://picture.de/image.png)');
});
这将在内存中创建一个新图像并使用 load 事件来检测何时加载 src。
编辑:在 Vanilla JavaScript 中,它看起来像这样:
var src = 'http://picture.de/image.png';
var image = new Image();
image.addEventListener('load', function() {
body.style.backgroundImage = 'url(' + src + ')';
});
image.src = src;
它可以抽象为返回Promise的方便函数:
function load(src) {
return new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener('load', resolve);
image.addEventListener('error', reject);
image.src = src;
});
}
const image = 'http://placekitten.com/200/300';
load(image).then(() => {
body.style.backgroundImage = `url(${image})`;
});
我有一个名为的jQuery 插件waitForImages
,它可以检测背景图像何时下载。
$('body')
.css('background-image','url(http://picture.de/image.png)')
.waitForImages(function() {
alert('Background image done loading');
// This *does* work
}, $.noop, true);
CSS 资产没有 JS 回调。
像这样的东西:
var $div = $('div'),
bg = $div.css('background-image');
if (bg) {
var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
$img = $('<img>').attr('src', src).on('load', function() {
// do something, maybe:
$div.fadeIn();
});
}
});
纯 JS 解决方案,将添加预加载器,设置背景图像,然后将其设置为垃圾收集及其事件侦听器:
简洁版本:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
let bgElement = document.querySelector("body");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
preloaderImg.addEventListener('load', (event) => {
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
更长一点的不透明度过渡:
const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
let bgElement = document.querySelector(".bg-lazy");
bgElement.classList.add("bg-loading");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
preloaderImg.addEventListener('load', (event) => {
bgElement.classList.remove("bg-loading");
bgElement.style.backgroundImage = `url(${imageUrl})`;
preloaderImg = null;
});
.bg-lazy {
height: 100vh;
width: 100vw;
transition: opacity 1s ease-out;
}
.bg-loading {
opacity: 0;
}
<div class="bg-lazy"></div>