带有z-Index的纯JS + CSS幻灯片:最后一张幻灯片上的小故障

时间:2018-02-10 23:21:30

标签: javascript css z-index slideshow transition

我尝试在JS + CSS中构建幻灯片,除了一个视觉故障外,它的效果非常好。过渡到最后一张幻灯片似乎有些不合时宜。

但我无法弄清问题是什么。如果我在最后一张幻灯片上注释掉“偏移”转换,则不会发生错误。

这是我所说的可待因:https://codepen.io/marianbreitmeyer/pen/paeYgZ

我提到的代码块就是这个:

const showNext = function() {
    clicked = true;
    for (i = 0; i <= slides.length-1; i++) {
        if( parseInt(slides[i].style.zIndex) === slides.length) {
            console.log(slides[i].innerHTML);
            triggerAnimation(slides[i], 'offcanvas');
        } else if (parseInt(slides[i].style.zIndex) === slides.length-1) {
            //the line below triggers the problem
            triggerAnimation(slides[i], 'offset');       
        }
    }
};

也许有经验的人可以帮助我:)。

1 个答案:

答案 0 :(得分:0)

您的代码可能更简单:

const btn = document.getElementsByClassName('arrow')[0];
const slides = document.getElementsByClassName('slide');

slides[slides.length - 1].classList.add('offset', 'next');

btn.addEventListener("click", function(e) {
  var o, n;
  for (var i = 0; i < slides.length; i++) {
    if (slides[i].classList.contains('offset')) {
      slides[i].classList.remove('offset', 'next')
      slides[i].classList.add('offcanvas');
      o = (slides[i - 1] || slides[slides.length - 1]);
      n = (slides[i - 2] || slides[slides.length + i - 2]);
    }
    if (slides[i].offsetLeft < -slides[i].offsetWidth) {
      slides[i].classList.remove('offcanvas', 'next');
    }
  }
  o.classList.add('offset');
  n.classList.add('next');
}, false);
.container {
  width: 100%;
  height: 100vh;
  background: brown;
  position: relative;
}

body {
  text-align: center;
  font-size: 2rem;
}

.slide {
  position: absolute;
  top: 0;
  left: 90%;
  width: 100%;
  height: 100%;
}

.slide:nth-child(1) {
  background: pink;
}

.slide:nth-child(2) {
  background: blue;
}

.slide:nth-child(3) {
  background: green;
}

.slide:nth-child(4) {
  background: grey;
}

.slide:nth-child(5) {
  background: yellow;
}

.slide.next {z-index:1}

.slide.offset {
  left: -10%;
  z-index: 2;
  transition: left .65s ease-in-out;
}

.slide.offcanvas {
  left: -110%;
  z-index: 2;
  transition: left .65s ease-in-out;
}

.arrow {
  position: absolute;
  right: 5%;
  top: 25px;
  z-index: 9;
  height: 50px;
  width: 50px;
  cursor: pointer;
}

.arrow:hover path {
  transform: translate(16px, 0px);
}

path {
  position: absolute;
  top: 0;
  left: 0;
  transition: all .2s ease-in-out;
}
<div class="container">

  <div class="slide">1 = pink</div>
  <div class="slide">2 = blue</div>
  <div class="slide">3 = green</div>
  <div class="slide">4 = grey</div>
  <div class="slide">5 = yellow</div>

  <svg xmlns="http://www.w3.org/2000/svg" class="arrow"><path d="M19.443 5.17L30.138 15.5H-.095v1h30.233L19.443 26.829l.696.719L32.095 16 20.139 4.451z"/></svg>

</div>