如何使用 CSS 和 JavaScript 创建弹出窗口?
点击按钮时会出现一个弹出窗口。在其中添加任何关键信息。要关闭弹出窗口,请在右上角设置一个叉号符号。但是,当鼠标光标位于网页上的其他位置时,弹出窗口通常会关闭。
设置一个按钮来打开弹出窗口
首先,创建一个用户点击以打开弹出窗口的按钮:
<button class="openPopUp">Open Popup</button>
设置弹出窗口的容器
为弹出窗口设置一个 div。在其中,为弹出窗口内容创建一个子容器。在其中,使用 × HTML 字符代码设置关闭符号:
<div class="popUp">
<div class="popupContent">
<span class="close">×</span>
<p>Sample text inside popup</p>
</div>
</div>
定位弹出窗口
要定位弹出窗口,请使用 position 属性并将其设置为 fixed。display 属性设置为 none,因为弹出窗口只有在点击按钮时才可见,否则保持隐藏:
.popUp {
text-align: center;
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
弹出窗口内容
在弹出窗口内,消息区域的宽度设置为 80%:
Within the popup, the message area is set with width 80%:
.popupContent {
font-size: 20px;
font-weight: bold;
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
设置关闭按钮的样式
使用 float 属性将关闭按钮定位到右侧:
.close {
color: rgb(255, 65, 65);
float: right;
font-size: 40px;
font-weight: bold;
}
悬停关闭按钮
这样,当悬停时,cursor 属性将设置为 pointer,使其看起来可点击:
.close:hover,
.close:focus {
color: #ff1010;
cursor: pointer;
}
示例
要使用 CSS 和 JavaScript 创建弹出窗口,代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
.popUp {
text-align: center;
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.popupContent {
font-size: 20px;
font-weight: bold;
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: rgb(255, 65, 65);
float: right;
font-size: 40px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #ff1010;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Popup Example</h1>
<button class="openPopUp">Open Popup</button>
<h2>Click on the above button to open the popup</h2>
<div class="popUp">
<div class="popupContent">
<span class="close">×</span>
<p>Sample text inside popup</p>
</div>
</div>
<script>
var popUp = document.querySelector(".popUp");
var btn = document.querySelector(".openPopUp");
var span = document.querySelector(".close");
btn.addEventListener("click", () => {
popUp.style.display = "block";
});
span.addEventListener("click", () => {
popUp.style.display = "none";
});
window.onclick = function(event) {
if (event.target == popUp) {
popUp.style.display = "none";
}
};
</script>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP