我正在尝试建立一个带有联系表的网站。我希望表单在单击菜单项时显示,并在用户在表单外部单击时关闭。我设法使javascript正确地打开了表单,但是当我单击任何表单子元素(例如输入)时,它会自动关闭。怎么了?
代码如下:
const hideContactForm = document.getElementById('kontakt');
const showContactForm = document.getElementById('vis_kontakt');
const form = document.getElementsByClassName('mail_form')[0];
const formChildren = form.children;
showContactForm.addEventListener('click', showForm);
hideContactForm.addEventListener('click', hideForm);
function showForm () {
hideContactForm.style.display = "flex";
}
function hideForm (event) {
for (let i = 0; i < formChildren.length; i++) {
if (event.target != form) {
hideContactForm.style.display = "none";
} else if (event.target == form) {
hideContactForm.style.display = "flex";
}
}
}
<div id="kontakt">
<div class="midtstill">
<form class="mail_form" action="kontakt.php" method="post">
<h2>Bestill opplæring</h2>
<input id="navn" type="text" name="name" value="" placeholder="Navn..">
<input id="email" type="email" name="email" value="" placeholder="E-mail..">
<input id="tlf" type="tel" name="tlf" value="" placeholder="Tlf..">
<textarea id="melding" name="message" rows="6" cols="40" placeholder="Melding.."></textarea>
<button type="submit" name="button">Kontakt meg</button>
</form>
</div>
</div>