gpt4 book ai didi

javascript - 使用 Javascript 表单验证更改 CSS

转载 作者:行者123 更新时间:2023-11-28 12:35:55 24 4
gpt4 key购买 nike

我有一个被 div 覆盖的网站。当有人输入正确的密码时,我想让 div 消失。我使用 Javascript 验证表单并成功将该 div 的 CSSdisplay:block 更改为 display:none,但紧接在显示属性之后已更改,它再次更改回默认值。我想要它,这样如果密码正确,#overlay 的显示将永远设置为无。

表格。

<form id="overlay-form" name="overlay-form" method="post" onsubmit="validateForm();">
<input id="overlay-password" name="overlay-password" type="password">
<input type="submit" id="overlay-submit" value="Submit">
</form>

Javascript。

<script>
function validateForm() {
var x = document.forms["overlay-form"]["overlay-password"].value;
if (x == "password") {
document.getElementById('overlay').style.display = "none";
}
}
</script>

最佳答案

默认情况下,表单提交会重新加载页面(或重定向到操作 url,如果给定的话)。如果您想阻止这种默认行为,请将其添加到您的 javascript 中:

function validateForm(event) { // pass in the event as a parameter, this is the form submit

var x = document.forms["overlay-form"]["overlay-password"].value;
if (x == "password") {
document.getElementById('overlay').style.display = "none";
event.preventDefault(); // prevent the default behaviour here
}
}

关于javascript - 使用 Javascript 表单验证更改 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27636352/

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