gpt4 book ai didi

javascript - 使用按钮切换 2 个 DIVS(使用 Javascript、HTML 和 CSS)

转载 作者:太空宇宙 更新时间:2023-11-03 22:45:50 26 4
gpt4 key购买 nike

基本上我有 2 个 div,里面都有不同的内容,我想用一个按钮在它们之间切换。

我的 2 个 div 分别为“step1Content”和“step2Content”。

<div class = 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>

我给 step1Content 样式显示: block 。

.step1Content { display: block; }

我给 step2Content 样式显示:无。

.step2Content { display: none; }

我有一个按钮可以在这 2 个之间切换以显示或隐藏。

<button onclick = 'step2()'>2. Taskeros and Prices</button>

还有我的 javascript 函数:

function step2(){
document.getElementByClassName('step1Content').style.display = 'none';
document.getElementByClassName('step2Content').style.display = 'block';
}

您会认为结果还可以吧?不,当我点击按钮时,它实际上什么也没做。我不知道为什么,对此有任何帮助吗?

最佳答案

请记住

getElementsByClassName

将返回文档中具有指定类名的所有元素的集合,作为 NodeList 对象。

您可以使用 getElementByIdquerySelector

这是一个可行的解决方案。希望对您有所帮助!

function step2(){
if(document.querySelector('.step1Content').style.display === "none"){
document.querySelector('.step2Content').style.display = 'none';
document.querySelector('.step1Content').style.display = 'block';
}else{
document.querySelector('.step1Content').style.display = 'none';
document.querySelector('.step2Content').style.display = 'block';
}
}
.step1Content { display: block; }
.step2Content { display: none; }
<button onclick = 'step2()'>2. Taskeros and Prices</button>
<div class= 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>

关于javascript - 使用按钮切换 2 个 DIVS(使用 Javascript、HTML 和 CSS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42016690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com