Медленное обновление представления после изменения CSS с помощью прослушивателя событий при нажатии - PullRequest
0 голосов
/ 26 мая 2019

Я пишу свою собственную реализацию Lightbox.

Я хочу, чтобы кнопки «» скрывались при отображении первого или последнего изображения.

В настоящее время изображение обновляется мгновенно, тогда как обновление элемента управления занимает до 2 секунд. Что вызывает задержку здесь?

Мой HTML:

            <!-- START gallery -->
            <section class="content-gallery">
                <img class="gallery-item anim" src="img/photo/img_01.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_02.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_04.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_05.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_06.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_07.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_08.png" alt="">
                <img class="gallery-item anim" src="img/photo/img_09.png" alt="">
            </section>
            <!-- END gallery -->

            <!-- START lightbox -->
            <div class="gallery-lightbox">
                <i class="lightbox-exit fas fa-times"></i>
                <div class="lightbox-image"></div>
                <div class="lightbox-controls">
                  <i id="lbCtrlPrev" class="anim lbCtrl fas fa-chevron-left"></i>
                  <span class="lightbox-counter"></span>
                  <i id="lbCtrlNext" class="anim lbCtrl fas fa-chevron-right"></i>
                </div>
            </div>
           <!-- END lightbox-->

JavaScript:

// initiate constants
const galleryItems = document.querySelectorAll(".gallery-item");
const lightbox = document.querySelector(".gallery-lightbox");
const lbImgContainer = document.querySelector(".lightbox-image");
const lbExitCtrl = document.querySelector(".lightbox-exit");
const lbControls = document.querySelector(".lightbox-controls");
const lbCounter = document.querySelector(".lightbox-counter");
const lbCtrlNext = document.querySelector("#lbCtrlNext");
const lbCtrlPrev = document.querySelector("#lbCtrlPrev");

// Init click events for controls - Previous/Next item in Lightbox
lbCtrlNext.addEventListener("click", function () {
    lbNavigate("next");
});
lbCtrlPrev.addEventListener("click", function () {
    lbNavigate("prev");
});

// Navigate to previous/next gallery item in lightbox
function lbNavigate(direction) {
    let srcImg = galleryItems.item(lbImgContainer.counter[0]); // get currently displayed img from gallery
    let newImg = null; // prepare storage for new image
    if (direction == "next" && srcImg.nextElementSibling) {
        newImg = srcImg.nextElementSibling; // grab next item
    } else if (direction == "prev" && srcImg.previousElementSibling) {
        newImg = srcImg.previousElementSibling; // grab previous item
    }
    if (newImg) lbUpdate(newImg); // update LightBox view.
}

// Add image to the lightbox
function lbUpdate(img) {
    lbImgContainer.innerHTML = ""; // flush contents
    let newImg = lbImgContainer.appendChild(img.cloneNode(false)); // add image
    newImg.className = "lightbox-item anim"; // flush cSS
    lbImgContainer.counter = lbCounterUpdate(img); // get index position of current image eg. (0 / 11)
    updateCtrlView(lbImgContainer.counter[0], lbImgContainer.counter[1]); // update controls based on 1. current index, 2. total of items.
}

// Update controls if necessary
function updateCtrlView(pos, end) {
    lbCtrlPrev.style.visibility = "visible"; // default
    lbCtrlNext.style.visibility = "visible"; // default
    if (pos == 0) lbCtrlPrev.style.visibility = "hidden"; // Hide "Prev" control if first item displayed.
    if (pos == (end - 1)) lbCtrlNext.style.visibility = "hidden"; // Hide "Next" control if last item displayed.
}

// Setup Lightbox counter
function lbCounterUpdate(target) {
    if (target) {
        let lbItemCount = galleryItems.length; // Count all items in parent
        let lbItemIndex = indexOfChildInNode(galleryItems, target) // Get the index of current item
        lbCounter.innerHTML = `${lbItemIndex+1} / ${lbItemCount}`; // format string
        return [lbItemIndex, lbItemCount]; // return displayed item index and overall item count.
    }
}

// Find the index of the child in NodeList
function indexOfChildInNode(parent, target) {
    let counter = 0; // initiate counter
    for (let child of parent) {
        if (child == target) return counter; // compare target element to each child
        counter++;
    }
}

Это из-за цикла в функции indexOfChildInNode? Что за узкое место здесь?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...