简体   繁体   English

替换背景图像的流畅方法

[英]Smooth way to replace background-image

I'm quite new to jQuery and JS and been asked to write a script that will be loading background-image progressively - I mean that low quality image should appear immediately and when full size image is loaded should replace the small one. 我是jQuery和JS的新手,并被要求编写一个脚本来逐步加载background-image -我的意思是低质量的图像应立即出现,当加载完整尺寸的图像时应替换较小的图像。

I found some tips how to do something similar by layering <img /> on top of background-image however in my case i have to deal with background-image only, so I have made this: 我发现了一些技巧,可以通过在background-image之上分层<img />来做类似的事情,但是就我而言,我只需要处理background-image ,所以我做到了:

$('.img-loader').each(function(){
    var box = this;

    var smallImg = $(this).attr('style');
    var bigImg = smallImg.replace('.jpg)', 'big.jpg)');
    var imgUrl = bigImg.replace('background-image: url', '');
    var imgUrlS = imgUrl.replace(/[{()}]/g, '');
    console.log(imgUrlS);

    $('<img/>').attr('src', imgUrlS).load(function(){
        $(this).remove();
        $(box).attr('style', bigImg);
    });
})

The script basically does the job but in that moment when the image gets replaced there is a quite noticeable 'shake'. 该脚本基本上可以完成这项工作,但是在替换图像的那一刻,出现了非常明显的“抖动”。

Any ideas how to make transition smoother or anyone knows what causing this 'shake'? 有什么想法可以使过渡更顺畅,还是有人知道是什么导致了这种“震动”?

Edit: As suggested I'm adding a markup snipped of where script has to be applied. 编辑:根据建议,我添加了一个标记,其中标记了必须应用脚本的位置。

<div class="about__section__bgimage img-loader"
style="background-image: url(<?php echo $contentBlock->imageurl ?>)"></div>

I suggest you create two separate elements with the same size, overlapping each other, with position: absolute; 我建议您创建两个具有相同大小的独立元素,彼此重叠,并具有以下位置:绝对; make one of them visible with the original bg image (using opacity: 1). 使用原始bg图像(使用不透明度:1)使其中之一可见。 The second one invisible (using opacity:0) 第二个不可见(使用opacity:0)

Once the higher quality image is completely loaded, set the opacity of the original image to 0 and the new image to 1. 完全加载更高质量的图像后,将原始图像的不透明度设置为0,将新图像的不透明度设置为1。

use a css transition on the opacity property to make the opacities change smoothly. 在opacity属性上使用css过渡,以使不透明度平滑变化。

you have to use animation for this. 您必须为此使用动画。 Use any of them according to your scenario enjoy it !!! 根据您的情况使用其中任何一个,享受它! https://daneden.github.io/animate.css/ https://daneden.github.io/animate.css/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM