:::

6-2 讓滑動圖可以真的運作

  1. 之前的滑動圖是寫成一個js檔,圖片資訊 images 都是設在裡面,我們無法將取得的圖片數據傳入 js,這樣不方便使用,因此,我們請AI改寫成函數,以便在樣板中呼叫之,這樣就可以傳入圖片參數:
    以下是用來產生圖片輪播的js語法,請將之包裝成js函數,並能傳入images ,以方便使用
    const images = [
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+1', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+1' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+2', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+2' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+3', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+3' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+4', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+4' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+5', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+5' }
        ];
    let currentIndex = 0;
    let intervalId;
    const mainImage = document.getElementById('mainImage');
    const thumbnailContainer = document.getElementById('thumbnailContainer');
    function createThumbnails() {
        images.forEach((img, index) => {
            const thumbnail = document.createElement('img');
            thumbnail.src = img.thumb;
            thumbnail.alt = 縮圖 ${index + 1};
            thumbnail.className = thumbnail img-fluid mb-2 ${index === 0 ? 'active' : ''};
            thumbnail.onclick = () => showImage(index);
            thumbnailContainer.appendChild(thumbnail);
        });
    }
    function showImage(index) {
        currentIndex = index;
        mainImage.src = images[index].full;
        updateThumbnails();
        scrollThumbnail();
    }
    function updateThumbnails() {
        const thumbnails = thumbnailContainer.getElementsByClassName('thumbnail');
        Array.from(thumbnails).forEach((thumb, index) => {
            thumb.classList.toggle('active', index === currentIndex);
        });
    }
    function scrollThumbnail() {
        const activeThumbnail = thumbnailContainer.getElementsByClassName('active')[0];
        if (activeThumbnail) {
            if (window.innerWidth >= 768) {
                thumbnailContainer.scrollTop = activeThumbnail.offsetTop - thumbnailContainer.offsetTop;
            } else {
                thumbnailContainer.scrollLeft = activeThumbnail.offsetLeft - thumbnailContainer.offsetLeft;
            }
        }
    }
    function startCarousel() {
        stopCarousel();
        intervalId = setInterval(() => {
            currentIndex = (currentIndex + 1) % images.length;
            showImage(currentIndex);
        }, 3000);
    }
    function stopCarousel() {
        if (intervalId) {
            clearInterval(intervalId);
        }
    }
    function adjustLayout() {
        const isMobile = window.innerWidth < 768;
        thumbnailContainer.style.height = isMobile ? 'auto' : ${mainImage.offsetHeight}px;
        thumbnailContainer.style.overflowX = isMobile ? 'auto' : 'hidden';
        thumbnailContainer.style.overflowY = isMobile ? 'hidden' : 'auto';
        thumbnailContainer.style.whiteSpace = isMobile ? 'nowrap' : 'normal';
        Array.from(thumbnailContainer.getElementsByClassName('thumbnail')).forEach(thumb => {
            thumb.style.display = isMobile ? 'inline-block' : 'block';
            thumb.style.width = isMobile ? 'auto' : '100%';
            thumb.style.height = isMobile ? '75px' : 'auto';
            thumb.style.marginRight = isMobile ? '10px' : '0';
        });
        scrollThumbnail();
    }
    createThumbnails();
    showImage(0);
    startCarousel();
    
    mainImage.addEventListener('load', adjustLayout);
    window.addEventListener('resize', adjustLayout);
    
    thumbnailContainer.addEventListener('mouseenter', stopCarousel);
    thumbnailContainer.addEventListener('mouseleave', startCarousel);
    mainImage.addEventListener('mouseenter', stopCarousel);
    mainImage.addEventListener('mouseleave', startCarousel);

     

  2. 得到的回應如下,我們將之貼到 index.js 取代原有內容,並順便將檔案改名為 slider.js,這樣比較清楚用途:
    function createImageCarousel(images, mainImageId, thumbnailContainerId) {
        let currentIndex = 0;
        let intervalId;
        const mainImage = document.getElementById(mainImageId);
        const thumbnailContainer = document.getElementById(thumbnailContainerId);
    
        function createThumbnails() {
            images.forEach((img, index) => {
                const thumbnail = document.createElement('img');
                thumbnail.src = img.thumb;
                thumbnail.alt = `缩图 ${index + 1}`;
                thumbnail.className = `thumbnail img-fluid mb-2 ${index === 0 ? 'active' : ''}`;
                thumbnail.onclick = () => showImage(index);
                thumbnailContainer.appendChild(thumbnail);
            });
        }
    
        function showImage(index) {
            currentIndex = index;
            mainImage.src = images[index].full;
            updateThumbnails();
            scrollThumbnail();
        }
    
        function updateThumbnails() {
            const thumbnails = thumbnailContainer.getElementsByClassName('thumbnail');
            Array.from(thumbnails).forEach((thumb, index) => {
                thumb.classList.toggle('active', index === currentIndex);
            });
        }
    
        function scrollThumbnail() {
            const activeThumbnail = thumbnailContainer.getElementsByClassName('active')[0];
            if (activeThumbnail) {
                if (window.innerWidth >= 768) {
                    thumbnailContainer.scrollTop = activeThumbnail.offsetTop - thumbnailContainer.offsetTop;
                } else {
                    thumbnailContainer.scrollLeft = activeThumbnail.offsetLeft - thumbnailContainer.offsetLeft;
                }
            }
        }
    
        function startCarousel() {
            stopCarousel();
            intervalId = setInterval(() => {
                currentIndex = (currentIndex + 1) % images.length;
                showImage(currentIndex);
            }, 3000);
        }
    
        function stopCarousel() {
            if (intervalId) {
                clearInterval(intervalId);
            }
        }
    
        function adjustLayout() {
            const isMobile = window.innerWidth < 768;
            thumbnailContainer.style.height = isMobile ? 'auto' : `${mainImage.offsetHeight}px`;
            thumbnailContainer.style.overflowX = isMobile ? 'auto' : 'hidden';
            thumbnailContainer.style.overflowY = isMobile ? 'hidden' : 'auto';
            thumbnailContainer.style.whiteSpace = isMobile ? 'nowrap' : 'normal';
            Array.from(thumbnailContainer.getElementsByClassName('thumbnail')).forEach(thumb => {
                thumb.style.display = isMobile ? 'inline-block' : 'block';
                thumb.style.width = isMobile ? 'auto' : '100%';
                thumb.style.height = isMobile ? '75px' : 'auto';
                thumb.style.marginRight = isMobile ? '10px' : '0';
            });
            scrollThumbnail();
        }
    
        createThumbnails();
        showImage(0);
        startCarousel();
    
        mainImage.addEventListener('load', adjustLayout);
        window.addEventListener('resize', adjustLayout);
        thumbnailContainer.addEventListener('mouseenter', stopCarousel);
        thumbnailContainer.addEventListener('mouseleave', startCarousel);
        mainImage.addEventListener('mouseenter', stopCarousel);
        mainImage.addEventListener('mouseleave', startCarousel);
    
        // 返回一些公共方法,以便外部控制
        return {
            showImage,
            startCarousel,
            stopCarousel
        };
    }

    這是另一個版本,只要一個參數即可:

    function initImageCarousel(images) {
        let currentIndex = 0;
        let intervalId;
        const mainImage = document.getElementById("mainImage");
        const thumbnailContainer = document.getElementById("thumbnailContainer");
    
        function createThumbnails() {
            images.forEach((img, index) => {
                const thumbnail = document.createElement("img");
                thumbnail.src = img.thumb;
                thumbnail.alt = `縮圖 ${index + 1}`;
                thumbnail.className = `thumbnail img-fluid mb-2 ${index === 0 ? "active" : ""
                    }`;
                thumbnail.onclick = () => showImage(index);
                thumbnailContainer.appendChild(thumbnail);
            });
        }
    
        function showImage(index) {
            currentIndex = index;
            mainImage.src = images[index].full;
            updateThumbnails();
            scrollThumbnail();
        }
    
        function updateThumbnails() {
            const thumbnails = thumbnailContainer.getElementsByClassName("thumbnail");
            Array.from(thumbnails).forEach((thumb, index) => {
                thumb.classList.toggle("active", index === currentIndex);
            });
        }
    
        function scrollThumbnail() {
            const activeThumbnail =
                thumbnailContainer.getElementsByClassName("active")[0];
            if (activeThumbnail) {
                if (window.innerWidth >= 768) {
                    thumbnailContainer.scrollTop =
                        activeThumbnail.offsetTop - thumbnailContainer.offsetTop;
                } else {
                    thumbnailContainer.scrollLeft =
                        activeThumbnail.offsetLeft - thumbnailContainer.offsetLeft;
                }
            }
        }
    
        function startCarousel() {
            stopCarousel();
            intervalId = setInterval(() => {
                currentIndex = (currentIndex + 1) % images.length;
                showImage(currentIndex);
            }, 3000);
        }
    
        function stopCarousel() {
            if (intervalId) {
                clearInterval(intervalId);
            }
        }
    
        function adjustLayout() {
            const isMobile = window.innerWidth < 768;
            thumbnailContainer.style.height = isMobile
                ? "auto"
                : `${mainImage.offsetHeight}px`;
            thumbnailContainer.style.overflowX = isMobile ? "auto" : "hidden";
            thumbnailContainer.style.overflowY = isMobile ? "hidden" : "auto";
            thumbnailContainer.style.whiteSpace = isMobile ? "nowrap" : "normal";
            Array.from(thumbnailContainer.getElementsByClassName("thumbnail")).forEach(
                (thumb) => {
                    thumb.style.display = isMobile ? "inline-block" : "block";
                    thumb.style.width = isMobile ? "auto" : "100%";
                    thumb.style.height = isMobile ? "75px" : "auto";
                    thumb.style.marginRight = isMobile ? "10px" : "0";
                }
            );
            scrollThumbnail();
        }
    
        createThumbnails();
        showImage(0);
        startCarousel();
    
        mainImage.addEventListener("load", adjustLayout);
        window.addEventListener("resize", adjustLayout);
    
        thumbnailContainer.addEventListener("mouseenter", stopCarousel);
        thumbnailContainer.addEventListener("mouseleave", startCarousel);
        mainImage.addEventListener("mouseenter", stopCarousel);
        mainImage.addEventListener("mouseleave", startCarousel);
    }
    

     

  3. 修改 templates/index.tpl 在載入 footer.tpl 的地方,刪掉 my_js 的參數,因為我們要在更早之前就引入 slider.js,而非在頁尾。
    {include file="footer.tpl"}

     

  4. 最後修改 templates/slider.tpl,我們引入 slider.js,讓函數可以讀得到,之後便可給欲顯示的圖片資料,並呼叫該函數:
    <div class="alert alert-info">
        <div class="row">
            <div class="col-md-3 order-md-1 order-2 mb-3 mb-md-0">
                <div class="thumbnail-container" id="thumbnailContainer">
                    <!-- 縮圖將通過 JavaScript 動態添加 -->
                </div>
            </div>
            <div class="col-md-9 order-md-2 order-1">
                <img id="mainImage" src="https://fakeimg.pl/800x600/cccccc/909090?text=Image+1" alt="主圖片">
            </div>
        </div>
    </div>
    <script src="slider.js"></script>
    <script>
        const images = [
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+1', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+1' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+2', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+2' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+3', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+3' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+4', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+4' },
        { thumb: 'https://fakeimg.pl/100x75/cccccc/909090?text=Image+5', full: 'https://fakeimg.pl/800x600/cccccc/909090?text=Image+5' }
        ];
        // 講義版本的寫法 
        //const carousel = createImageCarousel(images, 'mainImage', 'thumbnailContainer');
    
        // 上課實做的寫法 
        const carousel = initImageCarousel(images);
    </script>

     

  5. 最後,只要想辦法讓系統可以自動產生 images 真實的內容即可。

:::

書籍目錄

展開 | 闔起

快速登入


https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D2022%26tbsn%3D55

計數器

今天: 3864386438643864
昨天: 2489248924892489
總計: 8025846802584680258468025846802584680258468025846