Как сохранить только одно определение видимым одновременно в этом примере:
Другими словами:
Нажатие на кнопку
i
должно переключить класс на себя и определение ниже термина и удалить классactive
из других кнопки иopen
класс из других определений .
document.querySelectorAll("dl").forEach(dl =>
dl.addEventListener("click", ({ target }) => {
if (!target.matches("button")) return
target.classList.toggle("active")
target.parentElement.nextElementSibling.classList.toggle("open")
})
)
dd {
visibility: hidden;
height: 0
}
.open {
visibility: visible;
height: auto
}
.active {
color: DeepSkyBlue
}
abbr {
pointer-events: none
}
<dl>
<dt>aluminum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>the chemical element of atomic number 13, a light silvery-grey metal.</dd>
<dt>silver
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious shiny greyish-white metal, the chemical element of atomic number 47.</dd>
<dt>gold
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a yellow precious metal, the chemical element of atomic number 79.</dd>
<dt>platinum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious silvery-white metal, the chemical element of atomic number 78.</dd>
</dl>
4 ответа
Вы должны скрыть опцию открытия, прежде чем открывать новую. Вы могли бы сделать так:
window.onload = function() {
document.querySelectorAll("dl").forEach(dl =>
dl.addEventListener("click", ({ target }) => {
if (!target.matches("button")) return
const dl = target.closest('dl');
// Check if there is an active button and remove active class
if (dl.querySelector('.active') != null) {
dl.querySelector('.active').classList.toggle('active');
}
// Check if there is an open dd and close it
if (dl.querySelector('.open') != null) {
dl.querySelector('.open').classList.toggle('open');
}
target.classList.toggle("active")
target.parentElement.nextElementSibling.classList.toggle("open")
})
)
}
dd {
visibility: hidden;
height: 0
}
.open {
visibility: visible;
height: auto
}
.active {
color: DeepSkyBlue
}
abbr {
pointer-events: none
}
<p>Car List.</p>
<p id="show"></p>
<p id="show1"></p>
<dl>
<dt>aluminum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>the chemical element of atomic number 13, a light silvery-grey metal.</dd>
<dt>silver
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious shiny greyish-white metal, the chemical element of atomic number 47.</dd>
<dt>gold
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a yellow precious metal, the chemical element of atomic number 79.</dd>
<dt>platinum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious silvery-white metal, the chemical element of atomic number 78.</dd>
</dl>
Это то же самое, но вы не обязаны проверять состояние каждый раз.
Вы можете просто использовать element.classList="";
, чтобы удалить все данные класса из элемента.
Нет, у вас нет «активного» и «открытого» класса для какого-либо элемента, вам нужно использовать .classList.add("open")
вместо .classList.toggle("open")
Проверь это:
document.querySelectorAll("dl").forEach(dl =>
dl.addEventListener("click", ({ target }) => {
document.querySelectorAll("dd").forEach(function(element) {
element.classList="";
});
document.querySelectorAll(".active").forEach(function(element) {
element.classList="";
});
if (!target.matches("button")) return
target.classList.add("active")
target.parentElement.nextElementSibling.classList.add("open")
})
)
dd {
visibility: hidden;
height: 0
}
.open {
visibility: visible;
height: auto
}
.active {
color: DeepSkyBlue
}
abbr {
pointer-events: none
}
<dl>
<dt>aluminum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>the chemical element of atomic number 13, a light silvery-grey metal.</dd>
<dt>silver
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious shiny greyish-white metal, the chemical element of atomic number 47.</dd>
<dt>gold
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a yellow precious metal, the chemical element of atomic number 79.</dd>
<dt>platinum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious silvery-white metal, the chemical element of atomic number 78.</dd>
</dl>
Вот более краткое решение, которое использует только класс open
для того, что вам нужно, и некоторые функции CSS и ES6.
Идея состоит в том, чтобы удалить open
для всех, а затем переключаться только на тот, на который нажали. Также вся вещь для удаления связана с помощью методов ES6.
Также обратите внимание на селектор CSS .open+dd
, так как у вас есть братья и сестры, а не класс контейнера (это было бы проще при таком подходе).
document.querySelectorAll("dl").forEach(dl =>
dl.addEventListener("click", ({ target }) => {
if (!target.matches("button")) return
if (!target.parentElement.classList.contains("open"))
[...target.parentElement.parentElement.children]
.filter(({ tagName }) => tagName.toLowerCase() == "dt")
.forEach(element => element.classList.remove("open"))
target.parentElement.classList.toggle("open")
})
)
dd {
visibility: hidden;
height: 0
}
.open + dd {
visibility: visible;
height: auto
}
.open button {
color: DeepSkyBlue
}
abbr {
pointer-events: none
}
<dl>
<dt>aluminum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>the chemical element of atomic number 13, a light silvery-grey metal.</dd>
<dt>silver
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious shiny greyish-white metal, the chemical element of atomic number 47.</dd>
<dt>gold
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a yellow precious metal, the chemical element of atomic number 79.</dd>
<dt>platinum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious silvery-white metal, the chemical element of atomic number 78.</dd>
</dl>
Это может быть решением. Вы можете перебрать элементы, которые содержат класс, который вы хотите переключить, если они есть, то переключите его
document.querySelectorAll("dl").forEach(dl =>
dl.addEventListener("click", ({ target }) => {
document.querySelectorAll(".open").forEach(function(element) {
if(element.classList.contains("open")){
element.classList.toggle("open");
}
});
document.querySelectorAll(".active").forEach(function(element) {
if(element.classList.contains("active")){
element.classList.toggle("active");
}
});
if (!target.matches("button")) return
target.classList.toggle("active")
target.parentElement.nextElementSibling.classList.toggle("open")
})
)
dd {
visibility: hidden;
height: 0
}
.open {
visibility: visible;
height: auto
}
.active {
color: DeepSkyBlue
}
abbr {
pointer-events: none
}
<body>
<dl>
<dt>aluminum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>the chemical element of atomic number 13, a light silvery-grey metal.</dd>
<dt>silver
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious shiny greyish-white metal, the chemical element of atomic number 47.</dd>
<dt>gold
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a yellow precious metal, the chemical element of atomic number 79.</dd>
<dt>platinum
<button type=button><abbr title="See Definition"><i>i</i></abbr></button></dt>
<dd>a precious silvery-white metal, the chemical element of atomic number 78.</dd>
</dl>
</body>
Похожие вопросы
Новые вопросы
javascript
Для вопросов, касающихся программирования в ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (исключая ActionScript). Этот тег редко используется отдельно, но чаще всего ассоциируется с тегами [node.js], [jquery], [json] и [html].