繁体   English   中英

如何在 Slider 中的 JavaScript 中更改文本和图像?

[英]How to make text and image change in JavaScript within a Slider?

我在这里有这个代码: https://codepen.io/double_milkshake/pen/VwZJjgq

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

const textElement = document.querySelector(".text");


let counter = 0;

nextBtn.addEventListener('click',nextSlide);
prevBtn.addEventListener('click',prevSlide);

function nextSlide() {



    container.animate([{opacity: '0.1'},{opacity: '1.0'}],{duration:500, fill: 'forwards'});

    if(counter === 4) {
        counter = -1;
    }

    counter++;

    container.style.backgroundImage = `url(img/bcg-${counter}.png)`


}


function prevSlide() {

    container.animate([{opacity: '0.1'},{opacity: '1.0'}],{duration:1000, fill: 'forwards'});

    if(counter === 0) {
        counter = 5;
    }

    counter--;

    container.style.backgroundImage = `url(img/bcg-${counter}.png)`

}

它是一个简单的图像 slider。 您看不到图像,因为代码是为本地驱动器上的图像制作的。 每次单击按钮时,计数器都会发生变化,因此图像也会发生变化。

现在我想在单击时更改文本。 但不确定如何开始这个,也许你们有什么想法?

还有任何建议,当我不知道我的文件夹中有多少图像时该怎么办。 目前它们被硬编码为 5。

非常感谢!

HTML 标记:

<div class="text" id="caption">
  This is image 1
</div>

Javascript

const nextBtn = document.querySelector('.nextBtn');
const prevBtn = document.querySelector('.prevBtn');
const container = document.querySelector('.images');

const textElement = document.querySelector(".text");


let counter = 0;

nextBtn.addEventListener('click',nextSlide);
prevBtn.addEventListener('click',prevSlide);

function nextSlide() { 

    container.animate([{opacity: '0.1'},{opacity: '1.0'}],{duration:500, fill: 'forwards'}); 

    if(counter==4)
        counter=-1;
    counter = setText(counter, "up");

    container.style.backgroundImage = `url(img/bcg-${counter}.png)`
}


function prevSlide() {

    container.animate([{opacity: '0.1'},{opacity: '1.0'}],{duration:1000, fill: 'forwards'});

    if(counter==-0)
        counter=5;
    counter = setText(counter, "down"); 

    container.style.backgroundImage = `url(img/bcg-${counter}.png)`
}

function setText(cntr, direction){

    if(direction=="up") {
        cntr++;     
    } else {
        cntr--;     
    }
    if(cntr==0){
        document.getElementById("caption").innerHTML = "This is image 1";
    } else if(cntr==1){
        document.getElementById("caption").innerHTML = "This is image 2";
    } else if(cntr==2){
        document.getElementById("caption").innerHTML = "This is image 3";
    } else if(cntr==3){
        document.getElementById("caption").innerHTML = "This is image 4";
    } else if(cntr==4){
        document.getElementById("caption").innerHTML = "This is image 5";
    } 

    return cntr;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM