猿问

如何使这个手动和自动?

我有这个代码,它基本上改变了用户屏幕上的文本和图像。我想通过单击事件手动执行此操作。但我不能,有人可以帮我吗?请


let i = 0;

let img = 0;

let images = [

  '...',

  '...',

  '...',

  '...',

  '...',

  '...'

];


let textArrayImg = [

  "Moda",

  "Beleza",

  "Comportamento",

  "Decoração",

  "Entretenimento",

  "Bem-Estar"

];



let textImg = document.querySelector('.textImg');

let btnPrev = document.querySelector('.btnPrev');

let btnNext = document.querySelector('.btnNext');




function changeImg(){

  document.querySelector('.slide').src = images[img];

  textImg.textContent = textArrayImg[i];


  if(img < textArrayImg.length - 1){

    img++;

  }else {

    img = 0;

  }


  if(i < images.length - 1){

    i++;

  }else {

    i = 0;

  }


  setTimeout(changeImg, 3000);

}


changeImg();




btnPrev.addEventListener('click', () => {


});


btnNext.addEventListener('click', () => {


});

我已经尝试了一些方法,但我想这样做,因为它让我更容易


摇曳的蔷薇
浏览 165回答 1
1回答

沧海一幻觉

让我们看看这段代码,它基本上每三秒调用一次img,并在 3 秒后自动增加 , 的计数function changeImg(){&nbsp; document.querySelector('.slide').src = images[img];&nbsp; textImg.textContent = textArrayImg[i];&nbsp; if(img < textArrayImg.length - 1){&nbsp; &nbsp; img++;&nbsp; }else {&nbsp; &nbsp; img = 0;&nbsp; }&nbsp; if(i < images.length - 1){&nbsp; &nbsp; i++;&nbsp; }else {&nbsp; &nbsp; i = 0;&nbsp; }&nbsp; setTimeout(changeImg, 3000);}现在这有点像你的问题,因为它并没有真正定义它应该如何改变,所以你可以向它添加一个变量,它表明它需要如何改变img计数function changeImg( inc )然后改变img正在改变的地方,添加inc到它现在,如果您使用上一个按钮,它可能会出现低于 0 的问题,因此,您现在也必须处理这种情况,例如img += inc;if (img >= textArrayImg.length) {&nbsp; img = 0;} else if (img < 0) {&nbsp; img = textArrayImg.length - 1;}但是,您仍然必须在短时间内处理 changeImg 的自动调用事件(您不想调用两次),因此我们应该在手动更改某些内容时重置计时器if (timer) {&nbsp; clearTimeout( timer );}timer = setTimeout( changeImg, 3000 ); // don't forget to declare timer where you have img and stuff但是,现在我们有点想念 changeImg 中的参数,我们可能不希望它用 -1 或手动 +1 自动调用,因此将其更改为setTimeout( function() { changeImg( 1 ) }, 3000 );并确保您的初始呼叫然后也将其更改为changeImg( 1 );这是在函数之外您的事件处理程序现在可以使用此功能btnPrev.addEventListener('click', () => {&nbsp; changeImg( -1 );});btnNext.addEventListener('click', () => {&nbsp; changeImg( 1 );});请注意,在您中,changeImg您不需要两者img和i作为计数器(我假设它们彼此之间有些联系,因此它们必须引用相同的索引?)所以最后,我想你会有这个// at the declaration partlet timer;// changes to the functionfunction changeImg( inc ){&nbsp; img+=inc;&nbsp; if (img < 0) {&nbsp; &nbsp; img = textArrayImg.length - 1;&nbsp; } else if (img >= textArrayImg.length) {&nbsp; &nbsp; img = 0;&nbsp; }&nbsp; document.querySelector('.slide').src = images[img];&nbsp; textImg.textContent = textArrayImg[img];&nbsp; if (timer) {&nbsp; &nbsp; clearTimeout( timer );&nbsp; }&nbsp; timer = setTimeout(() => changeImg(1), 3000);}// initial callchangeImg(0); // keep it as 0 to start with so it automatically sets the initial items there
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答