在前端开发中,实现输入弹出框通常会用到JavaScript结合HTML和CSS。以下是一种常见的实现方式:
一、基础概念
二、示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>输入弹出框示例</title>
<style>
/* 弹出框的基本样式 */
.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.5);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 30%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<button id="openModalBtn">打开输入弹出框</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<label for="inputField">请输入内容:</label>
<input type="text" id="inputField">
<button id="submitBtn">提交</button>
</div>
</div>
<script>
// 获取元素
const modal = document.getElementById('myModal');
const openModalBtn = document.getElementById('openModalBtn');
const closeBtn = document.getElementsByClassName('close')[0];
const submitBtn = document.getElementById('submitBtn');
// 打开弹出框函数
openModalBtn.onclick = function () {
modal.style.display = 'block';
}
// 关闭弹出框函数
closeBtn.onclick = function () {
modal.style.display = 'none';
}
// 点击提交按钮后关闭弹出框并可做进一步处理(这里简单打印输入内容)
submitBtn.onclick = function () {
const inputValue = document.getElementById('inputField').value;
console.log('输入的内容是:', inputValue);
modal.style.display = 'none';
}
// 点击弹出框外部区域关闭弹出框
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
</script>
</body>
</html>
三、优势
四、应用场景
领取专属 10元无门槛券
手把手带您无忧上云