我的顺风图像滑块的 JS 代码不起作用:/



我对整个编码主题都是新手。我的第一个"大"字项目我想建立一个简单的网站与一些功能。我尝试用顺风和JS实现一个图像滑块。但是这个准则不起作用。提前感谢您的帮助<3screenHTML和顺风:

<section>
<div>
<div class="relativ h-50 relative">
<ul id="slider">
<li class="relativ scale-50">
<img class="h-full w-full object-fill" src="./img/test.png" alt="" />
</li>
<li class="relativ hidden h-[50vh]">
<img class="h-full w-full object-fill" src="./img/logo1.png" alt="" />
</li>
<li class="relativ hidden h-[50vh]">
<img class="h-full w-full object-fill" src="./img/test.png" alt="" />
</li>
</ul>
<div class="absolute top-1/2 -translate-y-1/2 w-full  px-5">
<div class="my-auto flex w-full justify-between ">
<button onclick="prev()" class="rounded-full bg-slate-500 bg-opacity-80 p-3 shadow-lg">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="h-6 w-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<button onclick="next()" class="rounded-full bg-slate-500 bg-opacity-80 p-3 shadow-lg">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="h-6 w-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</svg>
</button>
</div>
</div>
</div>
</div>
</section>

JS:

// Image slider
currentSlideId = 1;
sliderElement = document.getElementById('slider');
totalSlides = sliderElement.childElementCount;

function next (){
if(totalSlides<currentSlideId){
currentSlideId++;
showSlide();
}

}
function prev(){
if(currentSlideId > 1){
currentSlideId--;
showSlide();
}
}
function showSlide(){
slides = getElementById('slider').getElementsByTagName('li');
for (let index = 0; index < totalSlides; i++){
const element = slide[index];
if(currentSlideId===index+1){
element.classList.remove('hidden')
}else{
element.classList.add('hidden')
}
}
}

我试着编辑我的代码,但它不会工作:/

首先,欢迎了解堆栈溢出。

我认为问题在于for循环内的showSlide函数,其中您编写的'element'变量:

slide[index]

但我认为应该是:

slides[index]

因为名称中没有变量

也像@BestCoderBoy推荐的那样,在使用变量之前初始化它总是好的,看起来你使用的是没有文档的getElementByID。

相关内容

最新更新