简单 JS 弹窗实现:带关闭按钮的弹窗代码示例
以下是一个简单的 JS 弹窗,点击按钮后将弹出一个带有关闭按钮的弹窗。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>JS弹窗</title>
<script src='popup.js'></script>
</head>
<body>
<button onclick='popup()'>点击这里弹出窗口</button>
</body>
</html>
JS:
function popup() {
// 创建遮罩层元素
var mask = document.createElement('div');
mask.style.position = 'fixed';
mask.style.top = '0';
mask.style.left = '0';
mask.style.width = '100%';
mask.style.height = '100%';
mask.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
mask.style.zIndex = '9999';
// 创建弹窗元素
var popup = document.createElement('div');
popup.style.position = 'fixed';
popup.style.top = '50%';
popup.style.left = '50%';
popup.style.width = '300px';
popup.style.height = '200px';
popup.style.marginLeft = '-150px';
popup.style.marginTop = '-100px';
popup.style.backgroundColor = '#fff';
popup.style.border = '1px solid #ccc';
popup.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.5)';
popup.style.zIndex = '10000';
// 创建关闭按钮
var closeBtn = document.createElement('button');
closeBtn.innerHTML = '关闭';
closeBtn.style.position = 'absolute';
closeBtn.style.top = '10px';
closeBtn.style.right = '10px';
closeBtn.addEventListener('click', function() {
document.body.removeChild(mask);
});
// 将关闭按钮添加到弹窗元素
popup.appendChild(closeBtn);
// 将遮罩层和弹窗元素添加到body
document.body.appendChild(mask);
document.body.appendChild(popup);
}
代码中首先创建了遮罩层和弹窗元素,并设置了它们的基本样式。然后创建了一个关闭按钮,并将其添加到弹窗元素中。最后,将遮罩层和弹窗元素添加到 body 中。
通过以上代码,你就可以轻松实现一个带关闭按钮的简单 JS 弹窗。
原文地址: https://www.cveoy.top/t/topic/lSmD 著作权归作者所有。请勿转载和采集!