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

发布于 2024-08-16 04:42:49 字数 207 浏览 6 评论 0原文

我在 标记上应用了以下 CSS 类:

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

如何使用 JavaScript/jQuery 判断背景图像已完成加载?

I have the following CSS class that I'm applying on a <td> tag:

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

How can I tell with JavaScript/jQuery that the background image finished loading?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

落日海湾 2024-08-23 04:42:49

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

例如:

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

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

For example:

var bgImg = new Image();
bgImg.onload = function(){
   myDiv.style.backgroundImage = 'url(' + bgImg.src + ')';
};
bgImg.src = imageLocation;
江心雾 2024-08-23 04:42:49

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

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

往事随风而去 2024-08-23 04:42:49

@Jamie Dixon - 他没有说他想对背景图像做任何事情,只是知道它何时加载......

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

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

$(function( )
{
    var a = new Image;
    a.onload = function( ){ /* do whatever */ };
    a.src = $( 'body' ).css( 'background-image' );
});
浅笑依然 2024-08-23 04:42:49

本文可能有所帮助你。相关部分:

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

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

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.

夜唯美灬不弃 2024-08-23 04:42:49

onload 的一个问题是它会在数据准备好时触发,而不是在渲染完成时触发。

对于一个项目,我加载了一堆中型大图像。当图像加载时,人们会以一种碎片的方式获得图像“突然出现”的效果。

通过使用 onload解码

至于问题:“我如何知道背景图像已完成加载?”。它可以有多种解释;但如果人们正在寻找完成的渲染,这就是对这个问题的攻击。

简化:


img.onload = () => {
    some_elm.style.backgroundImage = 'url(' + some_src + ')';
    img.decode().then(some_function).catch(some_function);
}
img.onerror = some_function;
img.src = some_src;

其中 some_function 只是检查所有加载图像的计数器,但当然也可以用于一个图像。

我猜很可能是 decode() 的开销导致它流动良好,但效果很好。

发现它对于加载 元素(仅使用 decode)和背景(onload + 解码)。


然后,人们可以做任何事情,从简单地向包装器添加一个类或添加一些奇特的效果 - 例如以有序的方式逐个图像淡入淡出等。

另请注意 decode() 的浏览器兼容性

One issue with onload is that it fires when the data is ready, not when it is done rendering.

For one project I load a bunch of medium large images. As the images are loading one get the effect of images “popping into existence” in a fragmented way.

Solved this by using a combination of onload and decode.

As for Q: “How can I tell that the background image finished loading?”. It can be interpreted in several ways; but if one is looking for finished rendering this is an attack on that issue.

Simplified:


img.onload = () => {
    some_elm.style.backgroundImage = 'url(' + some_src + ')';
    img.decode().then(some_function).catch(some_function);
}
img.onerror = some_function;
img.src = some_src;

Where some_function simply checks a counter on all the images loaded, but can of course also be used for one image.

Guess it can easily be the overhead of decode() that causes it to flow nice, but have worked very well.

Have found it to work nice both for loading <img> elements, (using decode only), and backgrounds (onload + decode).


Then one can do anything from simply adding a class to a wrapper or add some fancy effects - for example fading in image by image in ordered fashion etc.

Also note Browser Compatibility for decode().

网白 2024-08-23 04:42:49

您还可以提供一个函数,只需用 div/background 替换 img 标签,这样您就可以从 onload 属性和 div 的灵活性中受益。

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

我的代码如下:

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

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.

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文