簡體   English   中英

圖片 slider 僅部分工作(Vanilla Javascript)

[英]Image slider is only partially working (Vanilla Javascript)

我正在處理 javascript 圖像 slider ,目前按鈕 go 從第一個圖像或索引 0 向前或向后。

這意味着如果我從后退開始,這就是發生的情況 0-3-2-1-NO IMAGES Just the Buttons 如果它是前進 0-1-2-3-NO IMAGES Just the Buttons 似乎是第二次迭代/循環由於某種原因我無法弄清楚。

此外,如果我從前進/后退開始並嘗試切換到后退/前進同樣的問題,沒有圖像只是按鈕出現。

我不確定這兩個是否相關,所以請幫忙。 這是 javascript

let imgEl = document.querySelectorAll("img");
let backBtnEl = document.querySelector(".back-btn");
let forwardBtnEl = document.querySelector(".forward-btn");
let currentIndex = 0;
let lengthImagesEl=imgEl.length;
function showSlide(currentIndex) {
    return imgEl[currentIndex].classList.add("showing");
}

function nextSlide() {
    imgEl[currentIndex].style.display="none";
    currentIndex = (currentIndex + 1) % lengthImagesEl;
    return showSlide(currentIndex);

}

function previousSlide() {
    imgEl[currentIndex].style.display = "none";
    currentIndex = (currentIndex + lengthImagesEl - 1) % lengthImagesEl;
    return showSlide(currentIndex);
 }

backBtnEl.addEventListener("click", previousSlide);
 
forwardBtnEl.addEventListener("click", nextSlide);
    

這是 HTML - 只有第一個圖片鏈接有效(道歉)

<!DOCTYPE html>
    <html>
      <head>
        <title>Slideshow</title>
        
        <link
          rel="stylesheet"
          href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
          crossorigin="anonymous"
        />
        <link rel="stylesheet" href="style.css" />
      </head>
      <body>
        <!-- Write your HTML in here -->
        <div class="img-container">
          <img class ="showing" src="https://images.unsplash.com/photo-1564349683136-77e08dba1ef7?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8cGFuZGFzfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="panda naps on branch">
          <img src="" alt="panda chilling">
          <img src="" alt="panda snack time">
          <img src="" alt="curious panda">
        </div>
        
        <div class="btn-container">
          <button class="back-btn">Back</button>
          <button class="forward-btn">Forward</button>
        </div>
       
        <script src="slideshow.js"></script>
      </body>
    </html>

這是 CSS

img{
    width:100%;
    height:550px;
    margin:5px;
    display:none;
}
.showing {
    display:block;
}

button {
    display:inline-flex;
    height: 30px;
    background-color:orange;
   }

已修復 似乎一旦顯示不顯示,它就無法返回“顯示”,所以我添加了一行代碼,它工作了 imgEl[currentIndex].classList.toggle("showing"); 而不是 imgEl[currentIndex].style.display = "none";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM