基本上我有 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 对象。
您可以使用 getElementById 或 querySelector
这是一个可行的解决方案。希望对您有所帮助!
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/