我是js新手,了解不多。前不久在一个网站上用js做了一个模态窗口(弹出),想用同样的代码制作点击div时弹出的元素,结果点击div时没有任何反应,控制台中甚至没有错误。在浏览器中手动添加开放类时,出现弹窗,可能是代码有问题?
html
<div class="questions" id="first-question">
<span class="play" id="first-question-text">Как начать играть?</span>
<img src="icons/arrow_drop_down.png" id="arrow-drop">
<div class="reply" id="reply1">
<span class="reply-text" id="text-1">Lorem ipsum dolor sit amet.</span>
</div>
CSS
.questions{
background-color: rgba(166, 149, 101, 0.50);
width: 100%;
height: 50px;
border-radius: 15px;
cursor: pointer;
transition: 0.3s;
}
.questions:hover{
opacity: 0.7;
}
#arrow-drop{
width: 35px;
height: 32px;
fill: white;
margin-top: 10px;
position: absolute;
margin-left: 395px;
}
#reply{
visibility: hidden;
color: white;
background-color: rgba(166, 149, 101, 0.50);
width: 100%;
margin-top: 50px;
}
#reply.open{
visibility: visible;
opacity: 1;
}
js
document.getElementById("first-question").addEventListener("click",function(){
document.getElementById("reply1").classList.add("open")
})
document.getElementById("first-question").addEventListener("click",function(){
document.getElementById("reply1").classList.remove("open")
})
单击时
open
,会添加一个类并立即删除。使用
classList.toggle
代替两个classList.add("open")
andclassList.remove("open")