要在不下载的情况下显示网络图片内容,可以使用以下技术实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Load Images</title>
<style>
img {
width: 100%;
height: auto;
display: block;
opacity: 0;
transition: opacity 0.5s;
}
img.loaded {
opacity: 1;
}
</style>
</head>
<body>
<img data-src="https://example.com/image1.jpg" alt="Image 1">
<img data-src="https://example.com/image2.jpg" alt="Image 2">
<img data-src="https://example.com/image3.jpg" alt="Image 3">
<script>
document.addEventListener("DOMContentLoaded", function() {
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.onload = () => img.classList.add('loaded');
observer.unobserve(img);
}
});
}, { threshold: 0.1 });
images.forEach(img => observer.observe(img));
});
</script>
</body>
</html>
onload
事件确保图片按顺序加载。通过以上方法,可以在不下载的情况下显示网络图片内容,提升用户体验和页面加载速度。
领取专属 10元无门槛券
手把手带您无忧上云