【问题标题】:Avoid flickering while loading background image with actual and fall back image使用实际和后备图像加载背景图像时避免闪烁
【发布时间】:2018-09-13 22:48:03
【问题描述】:

我正在使用下面的逻辑来加载带有回退默认图像的背景图像,以防第一张图像不可用。此图像是动态图像,它会逐页更改,有时可能不存在。因此将显示默认值。这很好,逻辑按预期工作。

但是,第一次加载页面时,浏览器会显示默认图像几秒钟,然后加载实际图像,因为它会闪烁。

有人可以告诉我如何避免闪烁并先加载实际图像,然后再加载默认图像,以防第一张图像不可用

$(document).ready(function(){

        var imageUrl = 'https://res.cloudinary.com/ct-hero.jpg';
        var defaultImageUrl = './images/profile-hero-default.jpg';
        $(".hero-bg-video").css("background-image", 'url(' + imageUrl + '), url('+defaultImageUrl+')'); 
    })

【问题讨论】:

标签: jquery html image css background-image


【解决方案1】:

你可以在 JS 中使用fadeIn。请检查以下代码。

JS

$(document).ready(function(){
    var imageUrl = 'https://res.cloudinary.com/openproperty/image/upload/q_auto/fox-hill-enfield-ct-hero.jpg';
        var defaultImageUrl ='https://www.fragrantnature.com/images/noimage.jpg';
        $.when($(".hero-bg-video").css("background-image", 'url(' + imageUrl + '), url('+defaultImageUrl+')')).done($(".hero-bg-video").fadeIn(4000)); 
    });

CSS

.hero-bg-overlay {
    background-color: rgba(0, 0, 0, 0.4);
    z-index: 1;
    width: 100%;
    height:400px;
}

.hero-bg-video {
    width: 100%;
    height: 400px;
    /*background-image: url(https://res.cloudinary.com/openproperty/image/upload/q_auto/briar-knoll-vernon-ct-hero.jpg), url(https://www.fragrantnature.com/images/noimage.jpg);*/
    background-size: 100% 100%;
  transition: all 0.5s;
  display:none;
}

默认情况下隐藏 div。设置背景图片后,您可以淡入 div 以获得流畅的动画效果。

这是fiddle

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多