jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。动态图片通常指的是通过 JavaScript 或 jQuery 在网页上动态加载和显示的图片。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 图片轮播</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.slider {
width: 600px;
overflow: hidden;
}
.slider img {
width: 100%;
display: none;
}
</style>
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<script>
$(document).ready(function() {
let images = $('.slider img');
let index = 0;
function showImage() {
images.hide();
images.eq(index).show();
index = (index + 1) % images.length;
}
setInterval(showImage, 3000);
showImage();
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 图片懒加载</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
img {
width: 100%;
height: auto;
display: block;
}
</style>
</head>
<body>
<img data-src="image1.jpg" alt="Image 1">
<img data-src="image2.jpg" alt="Image 2">
<img data-src="image3.jpg" alt="Image 3">
<script>
$(window).scroll(function() {
$('img[data-src]').each(function() {
if ($(this).offset().top < $(window).scrollTop() + $(window).height()) {
$(this).attr('src', $(this).data('src')).removeAttr('data-src');
}
});
});
</script>
</body>
</html>
visibility: hidden;
和 opacity: 0;
,并在图片加载完成后逐渐显示。通过以上方法,可以有效解决 jQuery 动态图片相关的常见问题,提升用户体验和页面性能。
领取专属 10元无门槛券
手把手带您无忧上云