javascript怎么使用alert实现一个精美的弹窗

2024-04-09

要实现一个精美的弹窗,你可以使用CSS样式来美化alert弹窗的外观。以下是一个示例代码:

<!DOCTYPE html>
<html>
<head>
<style>
.alert {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.alert h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.alert p {
  margin: 10px 0;
  font-size: 16px;
  color: #666;
}

.alert button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.alert button:hover {
  background-color: #0056b3;
}
</style>
</head>
<body>

<button onclick="showAlert()">Show Alert</button>

<script>
function showAlert() {
  var modal = document.createElement('div');
  modal.className = 'alert';
  modal.innerHTML = '<h2>Welcome!</h2><p>This is a beautiful alert box.</p><button onclick="closeAlert()">Close</button>';
  document.body.appendChild(modal);
}

function closeAlert() {
  document.querySelector('.alert').remove();
}
</script>

</body>
</html>

在上面的示例中,我们定义了一个样式为alert的弹窗,并通过JavaScript动态创建了这个弹窗。点击按钮时会显示这个弹窗,点击弹窗上的按钮可以关闭弹窗。你可以根据需求修改样式和内容,实现更加精美的弹窗效果。