我正在尝试创建图像幻灯片。目前,我编写了一个简单的代码来显示图像。现在,当我将新图像添加到同一文件夹时,我必须再次更新用于显示新图像的代码。如何使其动态化,以便代码自动选择图像并显示在HTML页面中。
<body>
<div class="slideshow-container">
<div class="mySlides fade">
<img src="img_nature_wide.jpg" style="width:100%">
</div>
<div class="mySlides fade">
<img src="img_snow_wide.jpg" style="width:100%">
</div>
<div class="mySlides fade">
<img src="img_mountains_wide.jpg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<script>
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = slides.length
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
</script>
</body>
答案 0 :(得分:0)
(可选)如果不使用服务器端脚本,则可以使用JavaScript数组并插入图像。不适用于50张图像,这很麻烦。
document.addEventListener( 'DOMContentLoaded', function(){
// insert your images here
var imgs = [ 'one.jpg', 'two.jpg' ];
var div, img;
for( var x = 0; x < imgs.length;x++ ){
div = document.createElement('div');
div.className = 'mylides fade';
img = document.createElement('img');
img.src = imgs[x];
div.appendChild( img );
document.querySelector('.slideshow-container').insertBerofe( div, document.querySelector('.next') );
}
}, false
)