JavaScript点击按钮隐藏div后瞬间重现的问题解决
问题原因
按钮放在<form>标签内部时,默认类型是submit,点击后会触发表单提交动作,导致页面刷新——这就是div刚隐藏就立刻重新出现的核心原因。另外你用document.querySelector("div")会选中页面里第一个div(也就是包含img的内层div),不是你要隐藏的外层firstPage,这也是个需要修正的小问题。
解决方法
方法一:修改按钮类型为button
直接给按钮加上type="button",避免它触发表单提交:
<div onmouseover="firstPageDisplay();" id="firstPage"> <div><img id="imgs"></div> <div class="center"> <form class="center">Authentification<br> <p>Login</p> <input id="login" type="text"><br> <p>Password</p> <input id="password" type="password"><br><br> <!-- 新增type="button",取消默认提交行为 --> <button onclick="myFunction();" id="btnA" type="button">Se connecter</button> </form> </div> </div>
同时修正JS里的选择器,精准选中目标外层div:
function myFunction() { // 通过id选中要隐藏的div,避免选错 let x = document.getElementById("firstPage"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
方法二:阻止表单默认提交行为
如果需要保留按钮的submit类型(比如后续要处理表单提交逻辑),可以在点击事件里阻止默认行为:
先修改按钮的onclick,传入事件对象:
<button onclick="myFunction(event);" id="btnA">Se connecter</button>
然后更新JS函数:
function myFunction(event) { // 阻止表单提交的默认刷新行为 event.preventDefault(); let x = document.getElementById("firstPage"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
方法三:移除form标签(如果不需要表单提交功能)
如果这个表单只是用来排版,不需要提交数据,直接删掉<form>标签也能解决问题:
<div onmouseover="firstPageDisplay();" id="firstPage"> <div><img id="imgs"></div> <div class="center"> Authentification<br> <p>Login</p> <input id="login" type="text"><br> <p>Password</p> <input id="password" type="password"><br><br> <button onclick="myFunction();" id="btnA">Se connecter</button> </div> </div>
同样记得把JS里的选择器改成document.getElementById("firstPage")。
内容的提问来源于stack exchange,提问作者LearningCode
相关产品推荐
相关产品推荐

