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

标签 javascript html css

基本上我有 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/

相关文章:

javascript - 如何使用 JQuery 使一个类同时处于事件状态?

html - 如何使背景图像适合所有屏幕尺寸?

html - 如何摆脱我的移动应用程序 (Ionic) 顶部的空白区域?

javascript - 如何解决三星 Android 浏览器的问题?

html - 背景渐变溢出文本,但它不应该

仅在第一次单击时才可更改元素边距的 JavaScript 函数

javascript - contenteditable=true 元素上的文本建议

javascript - 未捕获的类型错误 : Cannot read property 'get' of undefined when detecting chrome extension

php - 解析输入以查看它是地址、邮政编码、城市还是州?

html - 在垂直方向制作 100% li 宽度