我在 Shopify 產品頁面中有 3 個手風琴,我打算在頁面加載時將第一個手風琴默認展開。頁面加載后,單擊其他手風琴應該會關閉所有以前打開的手風琴。我只想用純 JavaScript(沒有像 jQuery 這樣的庫)或 CSS 來做。我下面的代碼只是確保第一個手風琴顯示為展開。在查看頁面https://wv3yau73hiyf9fhv-458195004.shopifypreview.com中的手風琴后,您能否幫助更正我的代碼?
window.onload = function() {
var accItem = document.getElementsByClassName('accordion__item');
// Keep the first accordion open by default.
for (i = 0; i < accItem.length; i ) {
console.log("Within first for loop");
accItem[0].click();
accItem[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i ) {
console.log("Within second for loop");
accItem[i].className = 'accordion__item close';
}
if (itemClass == 'accordion__item close') {
this.parentNode.className = 'accordion__item open';
}
}
};
uj5u.com熱心網友回復:
使用頁面上的瀏覽器控制臺,我使用以下命令打開了第一個手風琴:
let allAccordions = document.querySelectorAll(".accordion__item");
allAccordions[0].click();
是的,回圈也是可能的:
for (var i = 0; i < allAccordions.length; i ) {
if (i == 0) {
allAccordions[i].click();
break; // only the first, can stop looping.
}
}
uj5u.com熱心網友回復:
最后,解決方案如下:
// Keep the first accordion open by default.
let allAccordions = document.querySelectorAll(".accordion__item");
if (allAccordions.length > 0) {
allAccordions[0].querySelector("input[type=radio]").checked = true;
}
// Capture click event for the accordions
allAccordions.forEach(element => {
element.addEventListener('click', function() {
let radioBtn = this.querySelector("input[type=radio]");
let clickedRadioName = radioBtn.getAttribute("name");
allAccordions.forEach(element => {
let elementRadioBtn = element.querySelector("input[type=radio]");
let elementRadioName = elementRadioBtn.getAttribute("name");
if ((elementRadioName != clickedRadioName) && elementRadioBtn.checked) {
element.querySelector("input[type=radio]").checked = false;
}
});
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461983.html
標籤:javascript jQuery css 网络 前端
上一篇:如何從鏈接中隱藏檔案夾名稱
下一篇:列印時溢位隱藏影像根本不顯示
