如何使用jQuery生成一个简单的弹出窗口
这个任务是使用jQuery生成一个弹出窗口。弹出窗口对于向网站的访问者展示重要信息非常有用。
方法:一个简单的流行可以通过使用jQuery的toggle()方法来实现,它在jQuery的hide()和show()功能之间切换,也就是说,它检查所使用的选择器的可见性。当选择器可见时,hide()方法会被运行,当选择器不可见时,show()会被运行。
如果点击显示弹出窗口按钮,它就会显示弹出窗口,如果点击关闭按钮,就会隐藏弹出窗口。
用于切换的选择器是”.content”,它包含关闭按钮和弹出窗口的主体。最初,为了在重新加载页面时隐藏弹出窗口,我们在样式标签中的.content类上使用了display: none属性。
现在,当用户点击显示弹出窗口按钮时,onclick事件调用togglePopup(),显示弹出窗口,当用户点击关闭按钮时,onclick事件再次调用togglePopup(),隐藏弹出窗口。
语法:
$(selector).toggle();
示例:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery cdn link -->
<script src=
"https://code.jquery.com/jquery-3.5.1.min.js">
</script>
<style type="text/css">
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 500px;
height: 200px;
text-align: center;
background-color: #e8eae6;
box-sizing: border-box;
padding: 10px;
z-index: 100;
display: none;
/*to hide popup initially*/
}
.close-btn {
position: absolute;
right: 20px;
top: 15px;
background-color: black;
color: white;
border-radius: 50%;
padding: 4px;
}
</style>
</head>
<body>
<button onclick="togglePopup()">show popup</button>
<!-- div containing the popup -->
<div class="content">
<div onclick="togglePopup()" class="close-btn">
×
</div>
<h3>Popup</h3>
<p>
jQuery is an open source JavaScript library
that simplifies the interactions between an
HTML/CSS document, or more precisely the
Document Object Model (DOM), and JavaScript.
Elaborating the terms, jQuery simplifies
HTML document traversing and manipulation,
browser event handling, DOM animations,
Ajax interactions, and cross-browser
JavaScript development.
</p>
</div>
<script type="text/javascript">
// Function to show and hide the popup
function togglePopup() {
$(".content").toggle();
}
</script>
</body>
</html>