2 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
您將在每次單擊時(shí)切換所有元素上的類.answer
。
您只需在下一個(gè)<p>
元素中切換它。
我做了這個(gè)小提琴來演示。
更新后的代碼:
const containerQs = document.querySelectorAll('.detail-questions');
containerQs.forEach(container => {
? container.addEventListener('click', () => {
? ? ? container.nextElementSibling.classList.toggle('active');
? })
})

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
我沒有使用display block inline,因?yàn)槲倚枰蜷_和關(guān)閉時(shí)的持續(xù)時(shí)間。我用簡(jiǎn)單的 javascript 代碼創(chuàng)建了一個(gè)非常簡(jiǎn)單的手風(fēng)琴,我沒有關(guān)注 css,因?yàn)槟憧梢苑胖萌魏文阆胍?css,我們的重點(diǎn)是 javascript 想法和簡(jiǎn)單的 css 代碼。height:0; transition: all 1s linear在 css 中使用而不是在 Javascript 中使用,您可以在 javascript 中height: 0使用更改為原始高度scrollHeight,即使您在 css put 中,它也會(huì)為您提供元素的主要高度height: 0。如果你有任何問題就問我。如果您愿意,我可以使用與我的代碼相同的想法來編輯您的代碼。
var opencloseques = document.getElementsByClassName("opencloseques");
for (let i = 0; i < opencloseques.length; i = i + 1) {
opencloseques[i].onclick = function () {
if (this.classList.contains("opened") == false) {
this.parentElement.getElementsByClassName("answer")[0].style.height = this.nextElementSibling.scrollHeight + "px";
this.classList.add("opened")
} else {
this.parentElement.getElementsByClassName("answer")[0].style.height = "0";
this.classList.remove("opened")
}
}
}
.questionanswer .answer {
height: 0;
overflow: hidden;
transition: all 0.3s linear;
}
<div class="all">
<div class="questionanswer">
<button class="opencloseques">Click Me<span class='span'>+</span></button>
<div class="answer">
<p>Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it </p>
</div>
</div>
<div class="questionanswer">
<button class="opencloseques">Click Me<span class='span'>+</span></button>
<div class="answer">
<p>Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it Welcome To my website i hope you enjoy it </p>
</div>
</div>
</div>
添加回答
舉報(bào)