Javascript 如何验证背景(css)图像已加载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1927610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:56:01  来源:igfitidea点击:

How to verify background (css) image was loaded?

javascriptjquerycssloadbackground-image

提问by thedp

I have the following CSS class

我有以下 CSS 类

.bg {
   background-image: url('bg.jpg');
   display: none;
}

that I'm applying on a TD tag.

我正在申请 TD 标签。

My question is how can I tell with JavaScript/jQuery that the background image finished loading?

我的问题是如何使用 JavaScript/jQuery 判断背景图像已完成加载?

Thank you.

谢谢你。

UPDATE: added display property. Since my main objective it toggle it into view.

更新:添加了显示属性。由于我的主要目标是将其切换到视图中。

回答by Jamie Dixon

The only way I know of to do this is to load the image using Javascript, and then set that image as the backgroud.

我所知道的唯一方法是使用 Javascript 加载图像,然后将该图像设置为背景。

For example:

例如:

var bgImg = new Image();
bgImg.onload = function(){
   myDiv.style.backgroundImage = 'url(' + bgImg.src + ')';
};
bgImg.src = imageLocation;

回答by Gausie

Give the class to a div with visibility:hiddenat the initial page load. That way, it'll already be in the browser cache when you assign the class to your table cell.

visibility:hidden在初始页面加载时将类分配给一个 div 。这样,当您将类分配给表格单元格时,它就已经在浏览器缓存中了。

回答by Dan Beam

@Jamie Dixon - he didn't say he wanted to do anything with the background image, just know when it's loaded...

@Jamie Dixon - 他没有说他想对背景图片做任何事情,只要知道它什么时候加载......

$(function( )
{
    var a = new Image;
    a.onload = function( ){ /* do whatever */ };
    a.src = $( 'body' ).css( 'background-image' );
});

回答by AJM

This article may help you. Relevant section:

这篇文章可能对你有所帮助。相关栏目:

// 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" )
        );
    }
);

Basically select the background-image and do the check to see it's loaded.

基本上选择背景图像并检查它是否已加载。

回答by Stéphane de Luca

You also can provide a function that simply replaces the img tag by the div/background so that you benefit from both the onload attribute and the flexibility of the div.

您还可以提供一个函数,通过 div/background 简单地替换 img 标签,以便您从 onload 属性和 div 的灵活性中受益。

Of course, you can fine tune the code to best suits your need, but in my case, I also make sure that either the width or the height is preserved for a better control of what I expect.

当然,您可以微调代码以最适合您的需要,但就我而言,我还确保保留宽度或高度以更好地控制我的期望。

My code as follows:

我的代码如下:

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