简体   繁体   English

动画原生延迟加载图像(loading='“lazy”)

[英]Animate native lazy load image (loading='“lazy”)

Currently, images with the attribute loading="lazy" ( https://web.dev/native-lazy-loading/ ) are displayed immediately when loaded, ie without fade-in effect.目前,具有loading="lazy" ( https://web.dev/native-lazy-loading/ ) 属性的图像在加载时立即显示,即没有淡入效果。

Is there a way to animate images with the loading="lazy" attribute when they are loaded and preferably without JavaScript?有没有办法在加载时使用loading="lazy"属性为图像设置动画,最好没有 JavaScript?

I know, there are many lazyloading JavaScript libraries, but just because loading is now done natively by the browser, the handling via JavaScript feels like a step back again.我知道,有许多延迟加载 JavaScript 库,但仅仅因为加载现在由浏览器本地完成,通过 JavaScript 处理感觉就像又退了一步。

I managed to use a simple jQuery solution, since its already used in my case:我设法使用了一个简单的 jQuery 解决方案,因为它已经在我的案例中使用:

 //fade in lazy loaded images
 $('article img').on('load', function(){
    $(this).addClass('loaded');
 });

The images have 0 opacity by default and opacity 1 from the new class默认情况下,图像的不透明度为 0,新的 class 的不透明度为 1

img{
    opacity: 0;
    transition: opacity 300ms ease-in-out;
}

img.loaded{
    opacity: 1;
}

This is not graceful as users w/o JS wont see the images... but frankly i don't care ^^ To be honest, who has JS disabled?这并不优雅,因为没有 JS 的用户不会看到图像……但坦率地说,我不在乎 ^^ 老实说,谁禁用了 JS?

Unfortunately it is not as simple as the simple jQuery solution above.不幸的是,它不像上面简单的 jQuery 解决方案那么简单。 .on('load') does not work properly for all Browsers (like Chrome) as discussed here: Check if an image is loaded (no errors) with jQuery .on('load')不适用于所有浏览器(如 Chrome),如下所述: 检查是否使用 jQuery 加载图像(无错误)

I think you have to use @keyframes, something like:我认为您必须使用@keyframes,例如:

@keyframes lazy-kf{
    from {opacity:0;}
    to {opacity:1;}
}
img[loading=lazy] {
    animation: lazy-kf 5s;
}

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

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