如何验证背景(CSS)图像加载?
-
20-09-2019 - |
题
我有以下CSS类
.bg {
background-image: url('bg.jpg');
display: none;
}
这我申请上的TD标记。
我的问题是我怎么能知道用JavaScript / jQuery的背景图像加载完毕?
感谢您。
更新:加入显示属性。 由于我的它的主要目标切换成图。
解决方案
我知道要做到这一点的唯一方法是使用Javascript加载图像,然后设置图像作为化背景
例如:
var bgImg = new Image();
bgImg.onload = function(){
myDiv.style.backgroundImage = 'url(' + bgImg.src + ')';
};
bgImg.src = imageLocation;
其他提示
提供的类与visibility:hidden
一个div在初始页面加载。这样一来,它会已经在浏览器缓存中,当你指定类的表格单元格。
@Jamie迪克森 - 他没有说他想做的事与背景图像什么,只是知道,当它的加载...
$(function( )
{
var a = new Image;
a.onload = function( ){ /* do whatever */ };
a.src = $( 'body' ).css( 'background-image' );
});
这文章可以帮助你。相关部分:
// Once the document is loaded, check to see if the
// image has loaded.
$(
function(){
var jImg = $( "img:first" );
// Alert the image "complete" flag using the
// attr() method as well as the DOM property.
alert(
"attr(): " +
jImg.attr( "complete" ) + "\n\n" +
".complete: " +
jImg[ 0 ].complete + "\n\n" +
"getAttribute(): " +
jImg[ 0 ].getAttribute( "complete" )
);
}
);
基本上选择背景图像,并执行检查,看它的加载。
您也可以提供一个功能,让你无论从onload属性和div的灵活性中受益,仅仅用DIV /背景替换img标签。
当然,你可以微调代码,以最适合您的需要,但对我来说,我也确保宽度或高度保存较好的控制我所期望的。
我的代码如下所示:
<img src="imageToLoad.jpg" onload="imageLoadedTurnItAsDivBackground($(this), true, '')">
<style>
.img-to-div {
background-size: contain;
}
</style>
<script>
// Background Image Loaded
function imageLoadedTurnItAsDivBackground(tag, preserveHeight, appendHtml) {
// Make sure parameters are all ok
if (!tag || !tag.length) return;
const w = tag.width();
const h = tag.height();
if (!w || !h) return;
// Preserve height or width in addition to the image ratio
if (preserveHeight) {
const r = h/w;
tag.css('width', w * r);
}
else {
const r = w/h;
tag.css('height', h * r);
}
const src = tag.attr('src');
// Make the img disappear (one could animate stuff)
tag.css('display', 'none');
// Add the div, potentially adding extra HTML inside the div
tag.after(`
<div class="img-to-div" style="background-image: url(${src}); width: ${w}px; height:${h}px">${appendHtml}</div>
`);
// Finally remove the original img, turned useless now
tag.remove();
}
</script>
不隶属于 StackOverflow