请写一个html点击文字弹出div弹窗的代码要求要有设置宽度和高度的并且要求不管宽度和高度有多大都是自适应居中的代码
以下是一个点击文字弹出div弹窗的HTML代码,其中包含设置宽度和高度,并且自适应居中的CSS样式:
<!DOCTYPE html>
<html>
<head>
<style>
/* 弹窗的样式 */
.popup {
display: none; /* 默认隐藏 */
position: fixed; /* 固定定位,覆盖在页面上方 */
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
text-align: center; /* 文字居中 */
z-index: 9999; /* 设置层级,确保弹窗在最上方 */
}
/* 弹窗内容的样式 */
.popup-content {
display: inline-block; /* 内容以块级元素展示 */
background-color: #fff; /* 弹窗内容背景色 */
padding: 20px; /* 弹窗内容内边距 */
border-radius: 5px; /* 弹窗内容圆角 */
margin: 20px auto; /* 上下左右居中 */
max-width: 80%; /* 最大宽度 */
max-height: 80%; /* 最大高度 */
overflow: auto; /* 超出部分滚动 */
}
/* 链接文字的样式 */
.popup-link {
cursor: pointer; /* 鼠标光标变为手型 */
color: blue; /* 链接文字颜色 */
text-decoration: underline; /* 链接文字下划线 */
}
</style>
</head>
<body>
<a class="popup-link">点击此处弹出弹窗</a>
<div class="popup">
<div class="popup-content">
<!-- 弹窗内容 -->
<h2>弹窗标题</h2>
<p>弹窗内容</p>
<button onclick="hidePopup()">关闭</button>
</div>
</div>
<script>
// 显示弹窗
function showPopup() {
document.querySelector('.popup').style.display = 'block';
}
// 隐藏弹窗
function hidePopup() {
document.querySelector('.popup').style.display = 'none';
}
// 监听点击事件,点击链接文字显示弹窗
document.querySelector('.popup-link').addEventListener('click', showPopup);
</script>
</body>
</html>
在上面的代码中,通过CSS样式中的margin: 20px auto;实现了居中显示。此外,通过max-width和max-height属性可以设置最大的宽度和高度,当内容超出时,会出现滚动条。
原文地址: https://www.cveoy.top/t/topic/i7nr 著作权归作者所有。请勿转载和采集!