<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<img src="占位图路径" data-src="真实图片路径">
function lazyLoad() { $("img").each(function() { var imgTop = $(this).offset().top; var scrollTop = $(window).scrollTop(); var windowHeight = $(window).height(); if (imgTop < scrollTop + windowHeight) { $(this).attr("src", $(this).data("src")); } }); } $(window).scroll(function() { lazyLoad(); });
$(document).ready(function() { lazyLoad(); });
<!DOCTYPE html> <html> <head> <title>懒加载图片</title> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script> <style> img { width: 200px; height: 200px; margin-bottom: 20px; } </style> </head> <body> <img src="占位图路径" data-src="图片1路径"> <img src="占位图路径" data-src="图片2路径"> <img src="占位图路径" data-src="图片3路径"> <img src="占位图路径" data-src="图片4路径"> <img src="占位图路径" data-src="图片5路径"> <script> function lazyLoad() { $("img").each(function() { var imgTop = $(this).offset().top; var scrollTop = $(window).scrollTop(); var windowHeight = $(window).height(); if (imgTop < scrollTop + windowHeight) { $(this).attr("src", $(this).data("src")); } }); } $(window).scroll(function() { lazyLoad(); }); $(document).ready(function() { lazyLoad(); }); </script> </body> </html>
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com