使用 TailwindCSS 和 Flowbite 將輪播新增到我的頁面。我還添加了一個切換開關元素,基本上允許我在輪播中的兩個項目之間循環(選中 = 幻燈片 2,未選中 = 幻燈片 1)。
這個可行 - 我陷入困境的是嘗試根據 localStorage 中該切換的存儲值將其設置為加載時的“幻燈片 2”。
我已驗證我的 localStorage 值是否已正確保存/檢索(作為“是”和“否”字串)。然後,我嘗試在加載時將輪播設定為幻燈片 1(“否”值)或幻燈片 2(“是”值),但無論我嘗試什麼,它始終顯示幻燈片 1。
我嘗試了「slideTo()」和「next()」方法,但似乎都不起作用(它們在更改事件中起作用,但在我的載入函數中不起作用)。
控制台中沒有錯誤。就像我說的,切換在頁面加載後工作正常,並在幻燈片之間正確循環,它只是沒有在頁面加載時設置正確的幻燈片(因此顯示的幻燈片與切換的準確設置不匹配)。 p>
Flowbite 輪播文件:https://flowbite.com/docs/components/carousel/
這是我的程式碼:
window.addEventListener('load', function () { show_loader("service-suspended-container"); // Sidebar Toggle Defaults and Handler const exclude_suspended_toggle = document.getElementById('exclude-suspended-toggle'); // Determine which slide to display based on user's preference var starting_item = 0; if (('metrics-exclude-suspended' in localStorage) && localStorage.getItem('metrics-exclude-suspended') === 'yes') { starting_item = 1; } const carousel_items = [ { position: 0, el: document.getElementById('carousel-item-1') }, { position: 1, el: document.getElementById('carousel-item-2') } ]; const options = { defaultPosition: starting_item } // Carousel object for controlling slide var carousel = new Carousel(carousel_items, options); // Ecclude suspended toggle handler exclude_suspended_toggle.addEventListener('change', (event) => { console.log("Event fired"); if (event.currentTarget.checked) { // Make toggle checked console.log("Toggle now checked"); localStorage.setItem('metrics-exclude-suspended', 'yes'); carousel.slideTo(1); } else { // Uncheck toggle console.log("Toggle now unchecked"); localStorage.setItem('metrics-exclude-suspended', 'no'); carousel.slideTo(0); } }); // Determine default check state of toggle and slide from user's preferences if (('metrics-exclude-suspended' in localStorage) && localStorage.getItem('metrics-exclude-suspended') === 'yes') { console.log("enabled from storage..."); // Make toggle checked exclude_suspended_toggle.checked = true; carousel.slideTo(1); } else { console.log("disabled from storage..."); // Uncheck toggle exclude_suspended_toggle.checked = false; carousel.slideTo(0); } });
P粉3919557632024-03-22 20:26:41
您正在以程式設計方式變更選取的屬性,這不會觸發變更事件。由於未觸發更改事件,因此不會呼叫事件偵聽器。
觸發更改事件的一種方法:
const changeEvent = new Event("change") exclude_suspended_toggle.dispatchEvent(changeEvent)
因此,在您的程式碼中,它將變為:
const changeEvent = new Event("change") // Determine default check state of toggle and slide from user's preferences if (('metrics-exclude-suspended' in localStorage) && localStorage.getItem('metrics-exclude-suspended') === 'yes') { console.log("enabled from storage..."); // Make toggle checked exclude_suspended_toggle.checked = true; exclude_suspended_toggle.dispatchEvent(changeEvent) } else { console.log("disabled from storage..."); // Uncheck toggle exclude_suspended_toggle.checked = false; exclude_suspended_toggle.dispatchEvent(changeEvent) }