用原生JavaScript写一个带表单的弹出窗口,点击表单中的确定,弹出框关闭
时间: 2024-05-29 16:12:08 浏览: 175
HTML代码:
```html
<button id="openModal">打开弹出窗口</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>弹出窗口</h2>
<form>
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">年龄:</label>
<input type="number" id="age" name="age"><br><br>
<button type="submit" id="submit">确定</button>
</form>
</div>
</div>
```
CSS代码:
```css
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 60%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
```
JavaScript代码:
```javascript
// 获取元素
var openModalBtn = document.getElementById("openModal");
var modal = document.getElementById("modal");
var closeModalBtn = document.getElementsByClassName("close")[0];
var submitBtn = document.getElementById("submit");
// 点击打开弹出窗口按钮
openModalBtn.onclick = function() {
modal.style.display = "block";
}
// 点击关闭按钮
closeModalBtn.onclick = function() {
modal.style.display = "none";
}
// 点击确定按钮
submitBtn.onclick = function() {
// 获取表单中的值
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
// 对表单进行简单校验
if (name === "" || age === "") {
alert("姓名和年龄不能为空!");
} else {
// 弹出框关闭
modal.style.display = "none";
}
}
// 点击弹出框外部区域,弹出框关闭
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
```
效果如下:
![弹出窗口效果图](https://i.imgur.com/9GOb0GS.gif)
阅读全文