Vanilla javascript 图像轮播在第一次加载时未初始化

问题描述

我的图像轮播在第一次加载页面时没有初始化有问题,我必须刷新页面才能使其工作(它应该开始自动移动并且播放暂停和左右按钮应该工作)。一旦我刷新,它就可以正常工作。

HTML:

<section id='container_four'>

    <section class='carousel'>

      <section class='slides'>
          <div class='slide'><img src='img/spain1.jpeg' alt=''></div>
          <div class='slide'><img src='img/spain2.jpeg' alt=''></div>
          <div class='slide'><img src='img/spain3.jpeg' alt=''></div>
          <div class='slide' id='slide-index-3'><img src='img/spain4.jpeg' alt=''></div>
          <div class='slide'><img src='img/spain5.jpeg' alt=''></div>
          <div class='slide'><img src='img/spain6.jpeg' alt=''></div>
          <div class='slide'><img src='img/spain7.jpeg' alt=''></div>
          
      </section>

      <section class='slide-controls'>
        <button class='prev-btn'><img src='img/arrow_left.png' alt='arrow left'></button>
        <button class='next-btn'><img src='img/arrow_right.png' alt='arrow right'></button>
      </section>

      <input type='image' class='pause' src='img/pause.png'>

    </section>

JS:

const carousel = document.querySelector('.carousel');
const slideGroup = document.querySelector('.slides');
const nextBtn = document.querySelector('.next-btn');
const prevBtn = document.querySelector('.prev-btn');
let playPause = document.querySelector('.pause');
let slide = document.querySelectorAll('.slide');
let index = 3;
let intervalId;

//--------------------------------------------
// Clone images
const cloneOne = slide[0].cloneNode(true);
const cloneTwo = slide[1].cloneNode(true);
const cloneThree = slide[2].cloneNode(true);
const cloneFour = slide[3].cloneNode(true);
const cloneFive = slide[4].cloneNode(true);
const clonesix = slide[5].cloneNode(true);
const cloneseven = slide[6].cloneNode(true);

// Add clones to start and end of slide group
slideGroup.prepend(cloneFour,cloneFive,clonesix,cloneseven);
slideGroup.append(cloneOne,cloneTwo,cloneThree,cloneFour); 

slide = document.querySelectorAll('.slide'); 

// Set the slide width
const width = slide[index].clientWidth; 
slideGroup.style.transform = `translateX(${-width * index}px)`;

// Start automatic loop on page load
const startSlide = () => intervalId = setInterval(nextSlide,2000); 
startSlide();
window.addEventListener('load',() => {
    console.log('worked')
})

// When click the arrows...
// Move to next slide
function nextSlide() {
    console.log('nextslide works')
    index >= slide.length - 4 ? false : index++;
    slideGroup.style.transform = `translateX(${-width * index}px)`;
    slideGroup.style.transition = '1s'; 
}
// Move to prevIoUs slide
function prevSlide() {
    index <= 0 ? false : index--;
    slideGroup.style.transform = `translateX(${-width * index}px)`;
    slideGroup.style.transition = '1s';
}
nextBtn.addEventListener('click',nextSlide);
prevBtn.addEventListener('click',prevSlide);

cloneOne.id = 'clone1';
cloneFive.id = 'clone5';
    
function transitionend() {
    console.log('transitionend works')
    if(slide[index].id === 'clone1') {
        slideGroup.style.transition = 'ease-in';
        index = 3;
        slideGroup.style.transform = `translateX(${-width * index}px)`; 
    }
    if(slide[index].id === 'clone5') {
        slideGroup.style.transition = 'none';
         index = 7;
        slideGroup.style.transform = `translateX(${-width * index}px)`;
    }
}
slideGroup.addEventListener('transitionend',transitionend); 

// When press play/pause button,start/stop and change icon
function playOrPause() {
    console.log('playpause works')
    if(!intervalId) {
        playPause.src = 'img/pause.png';
        return startSlide(); 
    } else {
        playPause.src = 'img/play.png';
        clearInterval(intervalId);
        intervalId = null;
    }
}
playPause.addEventListener('click',playOrPause)

// Play/pause button mouSEOver event
playPause.addEventListener('mouSEOut',() => playPause.style.opacity = '0');
playPause.addEventListener('mouSEOver',() => playPause.style.opacity = '1');

// Keyboard function
function onKeydown(e) {
    switch(e.key) {
        case 'ArrowLeft':
            prevSlide();
            break;
        case 'ArrowRight':
            nextSlide();
            break;
        case 32:
            e.preventDefault();
            playOrPause();
    }
}
document.addEventListener('keydown',onKeydown);

CSS:

#container_four {
  background-color: #DED6D3;
  padding: 5% 0%;
}
.carousel {
  width: 100vw;
  height: auto;
  margin: auto;
  position: relative;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
.slides {
  display: flex; 
} 
.slide {
  min-width: 25%;
}
.slide img {
  width: 80%; 
}
.slide-controls {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: transparent;
  width: 100%;
  display: flex;
  justify-content: space-between;
  border: 0;
}
.slide-controls img {
  width: 2vw;
  cursor: pointer;
}
.next-btn,.prev-btn {
  background: transparent;
  border: none;
  padding: 2vw;
}
.next-btn:focus,.prev-btn:focus {
  outline: none;
}
.play,.pause {
  opacity: 1;
  cursor: pointer;
  position: absolute;
  width: 4vw;
  outline: none;
  padding: 15% 25%;
}

我在每个函数添加了控制台日志,并发现 transitionend 事件侦听器不会触发。我什至尝试以不同的方式重写它。唯一让它着火的是我是否刷新浏览器!

对问题可能是什么有任何建议吗?我很困惑为什么 transitionend 事件在第一次加载时被阻止,但在刷新后可以访问......其他事件侦听器看起来正在第一次加载。

需要明确的是,此问题仅在页面第一次加载时发生,因此重新访问页面将正常工作。只有当您打开一个没有网站历史记录的新浏览器时,它才不起作用。

这是页面https://chunzg.github.io/carousel/ 代码的 Github 链接https://github.com/chunzg/carousel

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)