点击按钮显示表单故障排查及隐藏功能需求(Odin Project图书馆项目)
图书馆项目表单显示/隐藏功能修复
表单无法显示的问题修复
你的代码里有三个关键问题导致点击按钮表单不显示:
- JS语法错误:
addEventListener的回调函数没有正确闭合,最后一行应该是});而非};。 - 目标元素错误:CSS中默认隐藏的是表单的父容器
.form-popup,但你修改的是内部form元素的display属性,父容器仍处于隐藏状态,自然看不到表单。应该修改父容器的显示状态。 - HTML按钮冗余属性:按钮标签里的
button属性和onclick="openForm"属于多余内容,会和JS的事件监听冲突,直接移除即可。
提交后隐藏表单的实现
给表单添加submit事件监听,先阻止默认的表单提交行为(防止页面跳转),再将表单容器设为隐藏状态。
修正后的完整代码
HTML
<div class="head-box"> <h1>My Library</h1> </div> <div class="body-box"> <button id="addBook"><h2>Add Book</h2></button> </div> <!-----Form information-----> <div class="form-popup" id="formContainer"> <form action="example.com/path" class="form-container" id="popUpForm"> <input type="text" id="title" placeholder="Title"> <input type="text" id="author" placeholder="Author"> <input type="number" id="pages" placeholder="Pages"> <input type="checkbox" id="readOption" name="readOption"> <label for="readOption">Have you read it?</label> <button type="submit">Submit</button> </form> </div>
注:顺便修正了input的type属性——
author和pages不是合法的type,分别改为text和number更规范。
CSS
h1 { font-family: ohno-blazeface, sans-serif; font-weight: 100; font-style: normal; font-size: 8vh; color: #001D4A; } .head-box { background-color: #9DD1F1; display: flex; justify-content: center; } h2 { font-family: poppins, sans-serif; font-weight: 300; font-style: normal; font-size: 3vh; color: #c2e8ff; } button { height: 10vh; width: 20vh; font-size: 3vh; background-color: #27476E; border-radius: 22px; border-color: #daf1ff; border-width: 2px; border-style: solid; } button:hover { background-color: #192c44; } body { background-color: #9DD1F1; } .body-box { display: flex; justify-content: center; } /* The pop up form - hidden by default */ .form-popup { display: none; position: fixed; bottom: 0; right: 15px; border: 3px solid #f1f1f1; z-index: 9; } .form-container { display: block; max-width: 300px; padding: 10px; }
JavaScript
// 获取按钮和表单容器元素 const formContainer = document.getElementById("formContainer"); const addBookBtn = document.getElementById("addBook"); const popUpForm = document.getElementById("popUpForm"); // 点击按钮显示表单 addBookBtn.addEventListener("click", function() { formContainer.style.display = "block"; }); // 提交表单后隐藏表单 popUpForm.addEventListener("submit", function(e) { // 阻止默认提交行为 e.preventDefault(); // 隐藏表单容器 formContainer.style.display = "none"; // 这里可以添加处理表单数据的逻辑,比如获取输入值、添加到图书馆列表等 const title = document.getElementById("title").value; const author = document.getElementById("author").value; const pages = document.getElementById("pages").value; const isRead = document.getElementById("readOption").checked; console.log("新增书籍:", {title, author, pages, isRead}); });
内容的提问来源于stack exchange,提问作者Dilek
相关产品推荐
相关产品推荐

