用纯js写一个弹框包括弹框的样式
时间: 2024-03-25 07:39:12 浏览: 15
好的,以下是一个用纯JS写的带样式弹框的示例代码:
HTML:
```html
<button onclick="showAlert()">点击打开弹框</button>
```
JS:
```javascript
function showAlert() {
// 创建遮罩层元素
var mask = document.createElement('div');
mask.className = 'alert-mask';
// 创建弹框元素
var alertBox = document.createElement('div');
alertBox.className = 'alert-box';
// 创建标题元素
var title = document.createElement('h2');
title.innerHTML = '提示';
alertBox.appendChild(title);
// 创建内容元素
var content = document.createElement('p');
content.innerHTML = '这是一个弹框!';
alertBox.appendChild(content);
// 创建关闭按钮元素
var closeButton = document.createElement('button');
closeButton.innerHTML = '关闭';
closeButton.onclick = function() {
document.body.removeChild(mask);
};
alertBox.appendChild(closeButton);
// 将弹框元素添加到遮罩层中
mask.appendChild(alertBox);
// 将遮罩层添加到页面中
document.body.appendChild(mask);
}
```
CSS:
```css
.alert-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
}
.alert-box {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
border: 1px solid #ccc;
box-shadow: 0 0 10px #ccc;
padding: 20px;
}
.alert-box h2 {
margin-top: 0;
}
.alert-box button {
margin-top: 20px;
}
```
当点击页面上的按钮时,会弹出一个带遮罩层、标题、内容和关闭按钮的弹框,点击关闭按钮或遮罩层时会将弹框从页面中移除。弹框的样式可以根据需求进行修改。