前端之轮播图代码优化
1、html中固定多个img图片

const imges = document.querySelectorAll('.image');
let currentIndex = 0;
function showNextSlide() {imges[currentIndex].classList.remove('active');currentIndex = (currentIndex + 1) % imges.length;imges[currentIndex].classList.add('active');
}
setInterval(showNextSlide, 1000);
console.log(['Hello 笔.COOL 控制台'], imges);
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="stylesheet" href="./style.css" /></head><body><div class="card-container"><imgclass="image active"src="https://img.cdn1.vip/i/6900682318366_1761634339.webp"mode="scaleToFill"/><imgclass="image"src="https://img.cdn1.vip/i/6900682336dd2_1761634339.webp"mode="scaleToFill"/><imgclass="image"src="https://img.cdn1.vip/i/690068233d0cf_1761634339.webp"mode="scaleToFill"/></div><script src="./index.js"></script></body>
</html>
body {background-color: rgba(0, 0, 0, 0.5);
}
.card-container {position: relative;width: 100%;height: 200px;
}
.image {width: 100%;height: 100%;position: absolute;opacity: 0;transition: opacity 0.5s ease-in-out;
}
.image.active {opacity: 1;
}
3、js 动态 使一个img变换多个src
渐变动画不生效
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="stylesheet" href="./style.css" /></head><body><div class="card-container"><img class="image active" mode="scaleToFill" id="carousel" /></div><script src="./index.js"></script></body>
</html>
const img = document.getElementById('carousel');
let currentIndex = 0;
const imgUrls = ['https://img.cdn1.vip/i/6900682318366_1761634339.webp','https://img.cdn1.vip/i/6900682336dd2_1761634339.webp','https://img.cdn1.vip/i/690068233d0cf_1761634339.webp',
];
function showNextSlide() {currentIndex = (currentIndex + 1) % imgUrls.length;img.src = imgUrls[currentIndex];
}
setInterval(showNextSlide, 1000);
3、js 动态加载多个img
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="stylesheet" href="./style.css" /></head><body><div id="slides" class="card-container"></div><script src="./index.js"></script></body>
</html>
const imgContent = document.getElementById('slides');
const imgUrls = ['https://img.cdn1.vip/i/6900682318366_1761634339.webp','https://img.cdn1.vip/i/6900682336dd2_1761634339.webp','https://img.cdn1.vip/i/690068233d0cf_1761634339.webp',
];
imgUrls.forEach((src, index) => {const img = document.createElement('img');img.src = src;img.classList.add('image');if (index === 0) img.classList.add('active');imgContent.appendChild(img);
});
const imgs = document.querySelectorAll('.image');
let currentIndex = 0;
function showNextSlide() {imgs[currentIndex].classList.remove('active');currentIndex = (currentIndex + 1) % imgUrls.length;imgs[currentIndex].classList.add('active');
}
setInterval(showNextSlide, 1000);
console.log(['Hello 笔.COOL 控制台'], imges);
