html 模态窗口并传参数实现代码
时间: 2023-08-28 18:03:41 浏览: 39
以下是一个基于HTML、CSS和JavaScript实现模态窗口并传参数的示例代码:
HTML部分:
```html
<button onclick="openModal('Hello World!')">打开模态窗口</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<p id="modalText"></p>
</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: 80%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
```
JavaScript部分:
```javascript
function openModal(text) {
var modal = document.getElementById("myModal");
var modalText = document.getElementById("modalText");
modalText.innerHTML = text;
modal.style.display = "block";
}
function closeModal() {
var modal = document.getElementById("myModal");
modal.style.display = "none";
}
```
在示例代码中,点击按钮会调用`openModal`函数并传入一个字符串参数,该函数会将该字符串赋值给模态窗口中的`<p>`标签,并将模态窗口显示出来。模态窗口中的关闭按钮会调用`closeModal`函数,该函数会将模态窗口隐藏。