jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。jQuery 换图片通常是指通过 jQuery 来动态更改网页上的图片。
img
标签的 src
属性来更换图片。<!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>
</head>
<body>
<img id="myImage" src="image1.jpg" alt="图片1">
<button id="changeImage">换图片</button>
<script>
$(document).ready(function() {
$('#changeImage').click(function() {
$('#myImage').attr('src', 'image2.jpg');
});
});
</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>
</head>
<body>
<img id="myImage" src="image1.jpg" alt="图片1">
<script>
$(document).ready(function() {
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var index = 0;
setInterval(function() {
$('#myImage').attr('src', images[index]);
index = (index + 1) % images.length;
}, 3000);
});
</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>
#myImage {
transition: opacity 1s;
}
</style>
</head>
<body>
<img id="myImage" src="image1.jpg" alt="图片1">
<button id="changeImage">换图片</button>
<script>
$(document).ready(function() {
$('#changeImage').click(function() {
$('#myImage').fadeOut(500, function() {
$(this).attr('src', 'image2.jpg').fadeIn(500);
});
});
});
</script>
</body>
</html>
$(document).ready()
或 $(function() {})
。通过以上示例代码和解释,你应该能够理解并实现 jQuery 换图片的基本操作,并解决一些常见问题。
领取专属 10元无门槛券
手把手带您无忧上云