第一次单击元素不起作用,第二次单击起作用

时间:2021-01-09 07:04:35

标签: javascript html css console

https://alexkchapman.com/Vans.html

在我网站上的三张图片中的任何一张(以及移动设备上的导航按钮)上,第一次点击无效,但后续点击有效。控制台记录点击已注册,但图像未更改。

这是相关的js:

var slideIndex = [1, 1, 1];
/* Class the members of each slideshow group with different CSS classes */
var slideId = ["slides1", "slides2", "slides3"];
showSlides(1, 0);
showSlides(1, 1);
showSlides(1, 2);

function plusSlides(n, no) {
  showSlides(slideIndex[no] += n, no);
  console.log(n);
}

function showSlides(n, no) {
  var i;
  var x = document.getElementsByClassName(slideId[no]);
  if (n > x.length) {
    slideIndex[no] = 1
  }
  if (n < 1) {
    slideIndex[no] = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex[no] - 1].style.display = "block";
}

1 个答案:

答案 0 :(得分:0)

所以你的代码还不错,但是你应该通过 js 类选择器选择幻灯片,最终代码将如下所示: (我建议使用此代码而不是您的代码,因为您的代码很复杂)

// var slideIndex = [1, 1, 1];
// /* Class the members of each slideshow group with different CSS classes */
// var slideId = ["slides1", "slides2", "slides3"];
// showSlides(1, 0);
// showSlides(1, 1);
// showSlides(1, 2);
var slides = document.getElementsByClassName('slides');
var slideIndex = 0;

function plusSlides() {
  slideIndex++;
  showSlides(slideIndex);
}

function showSlides(Index) {
    if (Index >= slides.length) {
        slideIndex = 1;
    }
    if (Index < 0) {
        slideIndex = slides.length;
    }
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    slides[slideIndex].style.display = "block";
}
<div class="slideshow">
            <div class="slides fade"><img src="img/header.jpg" width="100%"></div>
            <div class="slides fade"><img src="img/header1.jpg" width="100%"></div>
            <div class="slides fade"><img src="img/header2.jpg" width="100%"></div>
            <div class="slides fade"><img src="img/header3.jpg"     width="100%"></div>
</div>

代码中的问题在注释中说明:

// Select slides via class!!!!!!!!!!!!

// var slideIndex = [1, 1, 1];
// /* Class the members of each slideshow group with different CSS classes */
// var slideId = ["slides1", "slides2", "slides3"];
// showSlides(1, 0);
// showSlides(1, 1);
// showSlides(1, 2);


// You only need to increment slideIndex and run showSlides again
function plusSlides(n, no) {
  showSlides(slideIndex[no] += n, no);
  console.log(n);
}

// here you only have to hide every slide and show the one with the index of slideIndex
function showSlides(n, no) {
  var i;
  var x = document.getElementsByClassName(slideId[no]); // big mistake
//   every thing below is fine
  if (n > x.length) {
    slideIndex[no] = 1
  }
  if (n < 1) {
    slideIndex[no] = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
//   execpt this line
  x[slideIndex[no] - 1].style.display = "block";
// should be like this
//   x[slideIndex].style.display = "block";
}