html5在搜索框里加模态框
时间: 2024-03-01 17:53:51 浏览: 18
在搜索框里加模态框可以通过以下步骤实现:
1. 创建一个搜索框的 HTML 元素,如下所示:
```
<input type="text" id="search-box" placeholder="Search...">
```
2. 创建一个模态框的 HTML 元素,如下所示:
```
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Modal content goes here...</p>
</div>
</div>
```
3. 使用CSS样式为模态框添加样式,如下所示:
```
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
```
4. 使用 JavaScript 代码为搜索框添加单击事件,以显示模态框,如下所示:
```
var modal = document.getElementById("myModal");
var btn = document.getElementById("search-box");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
```
上述代码将在单击搜索框时显示模态框,单击模态框右上角的“X”图标或模态框外的任何地方时,将关闭模态框。