当原始图像进入用户的视口时,我正在使用IntersectionObserver
另一个图像替换最初加载的图像。
我希望图像淡入,而不是直接替换。
我尝试将 Jquery 加载程序添加到图像中,但它没有按我的意愿工作。
function fadeIn(obj) {
$(obj).fadeIn(1000);
}
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
$(lazyImage).on('load', fadeIn(lazyImage));
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<img
class="lazy"
src="https://classroomclipart.com/christmas-tree-with-bright-lights-decoration-animated-clipart-motion-lights-gifts-presents-2.gif"
data-src="https://classroomclipart.com/TN_december-happy-holidays_2.jpg"
data-srcset="https://classroomclipart.com/sm-santa-claus-and-reindeer-singing-christmas-carols-clipart.jpg 2x, https://classroomclipart.com/TN_december-happy-holidays_2.jpg 1x"
width="100"
height="100"
>